如何在visual C ++ 2013中嵌套initializer_lists [英] How to do nested initializer_lists in visual C++ 2013

查看:142
本文介绍了如何在visual C ++ 2013中嵌套initializer_lists的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作在g ++和clang,使用嵌套的initializer_list的程序。在Visual C ++中,1D情况下工作,但2D嵌套initializer_list不。有没有使Visual C ++工作的窍门,或者这是一个在他们的实现中的错误?

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?

这是我的示例代码。如果我删除注释的行,它在Visual C ++ 2013。

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}) } );

语法可以乱七八糟( l * {2,1} )。

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

这篇关于如何在visual C ++ 2013中嵌套initializer_lists的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆