initializer_lists of streams(C 11)

我试图将可变数量的流传递给一个接受initializer_list但似乎不起作用的函数,并抛出initializer_list结构中的所有可能错误以及我的函数如何与一组ofstreams无法匹配任何错误定义的功能.

实际上是否可以在initializer_list中传递ofstreams的引用?

TEST.CPP

#include "extension.h"


ofstream outputFile, outputFile2;

int main(void) {

    outputFile.open(("data_1.txt");
    outputFile2.open("data_2.txt");
    writeSomething({outputFile, outputFile2});
    outputFile.close();
    outputFile2.close();
}

extension.h

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <string.h>
#include <initializer_list>

using namespace std;

void writeSomething(initializer_list<ofstream&> args);

extension.cpp

#include "extension.h"

void writeSomething(initializer_list<ofstream&> args) {
    for (auto f : args ) {
        f << "hello" << endl;
    }
}

最佳答案 clang 3.4(trunk 194324)产生一个非常清晰的错误消息:

initializer_list:54:23: error: ‘iterator’ declared as a pointer to a
reference of type
'std::basic_ofstream<char> &'
typedef const _E* iterator;

所以不,这是不可能的.另见Error: forming pointer to reference type ‘const std::pair&’… I can’t understand this error.

(由于某些内部编译器错误,gcc 4.7.2和4.8.1在此代码上崩溃.我已提交了bugreport.)

你可以做的是传递指针而不是引用,如下所示:

#include <fstream>
#include <initializer_list>

using namespace std;

void writeSomething(initializer_list<ofstream*> args) {
    for (auto f : args )
        *f << "hello" << endl;
}

int main() {
    ofstream outputFile("data_1.txt");
    ofstream outputFile2("data_2.txt");
    writeSomething({&outputFile, &outputFile2});
}

但是,我宁愿使用std :: vector.为此目的使用初始化列表非常奇怪,对我来说很困惑.

点赞