简体   繁体   中英

How to do nested initializer_lists in visual C++ 2013

I've got a program which works in g++ and clang, using a nested initializer_list. In Visual C++, the 1D case works, but a 2D nested initializer_list does not. Is there a trick to make Visual C++ work, or is this maybe a bug in their implementation?

Here's my example code. It works in Visual C++ 2013 if I remove the annotated line.

#include <iostream>
#include <initializer_list>

using namespace std;

template<class T>
void print(T val) {
    cout << val;
}

template<class T>
void print(initializer_list<T> lst) {
    bool first = true;
    cout << "[";
    for (auto i : lst) {
        if (!first) cout << ", ";
        print(i);
        first = false;
    }
    cout << "]";
}

template<class T>
void print(initializer_list<initializer_list<T>> lst) {
    bool first = true;
    cout << "[";
    for (auto i : lst) {
        if (!first) cout << ", ";
        print(i);
        first = false;
    }
    cout << "]";
}

int main()
{
    print({1, 2, 3});
    cout << endl;
    // Without this line, Visual C++ 2013 is happy
    print({{1, 2}, {3, 4, 5}, {6}});
}
template<class T>
std::initializer_list<T> list( std::initializer_list<T>&& l ) { return std::move(l); }

or something similar may at least give you the workaround:

print( { list({1,2}), list({3,2,1}) } );

the syntax can be messed around with ( l*{2,1} ) in a few ways as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM