班级成员初始化程序在VS 2013中失败 [英] In-class member initializer fails with VS 2013

查看:57
本文介绍了班级成员初始化程序在VS 2013中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望可以编译以下代码,但是Visual Studio 2013 Update 2给我一个错误,而g ++ 4.7可以很好地编译。

I expected the following code to compile, but Visual Studio 2013 Update 2 gives me an error, while g++ 4.7 compiles it fine.

using std::vector;
using std::string;

struct Settings
{
    vector<string> allowable = { "-t", "--type", "-v", "--verbosity" };
};

VS 2013编译失败:

VS 2013 compile fails with:


'std :: vector< std :: string,std :: allocator< _Ty>> :: vector':没有重载函数需要4参数

'std::vector<std::string,std::allocator<_Ty>>::vector' : no overloaded function takes 4 arguments

如果我按以下方式更改成员,则可以正常编译:

If I change the member as follows then it compiles fine:

vector<string> allowable = vector<string> { "-t", "--type", "-v", "--verbosity" };

我看过建议从Bjarne的常见问题解答,我查看了MSDN 页面关于VS 2013中已完成的C ++ 11功能,但我仍然感到困惑。它应该按原样编译,还是我错了,必须两次指定类型?

I've looked at the proposal linked from Bjarne's FAQ and I've looked at the MSDN page on completed C++11 features in VS 2013 but I'm still confused. Should it compile as is, or am I wrong and must specify the type twice?

推荐答案


  • 您显示的示例是完全有效的C ++,但没有适用于VC ++ 2013。

    • The example that you showed is perfectly valid C++, however it doesn't work for VC++2013.

      这是已知的 VC ++ 2013错误,自2013年10月31日以来已报告,其状态仍然有效。

      This is a known VC++2013 bug reported since 31/10/2013 and its status is still active.

      但是,您可以通过解决方法来克服它。正如 @ildjarn 所建议的那样,只需简单地添加一对大括号即可,您可以强制 initializer_list<>引发 std :: vector 构造函数,而不是其fill构造函数,如下例所示:

      However, you can surmount it by doing a work-around. As @ildjarn suggested, by simply putting an extra pair of curly braces you force initializer_list<> constructor of the std::vector to be evoked instead of its fill constructor, like the example below:

         #include <string>
         #include <vector>
         #include <iostream>
      
         struct Settings {
           std::vector<std::string> allowable = {{"-t", "--type", "-v", "--verbosity"}};
         };
      
         int main() {
           Settings s;
           for (auto i : s.allowable) std::cout << i << " ";
           std::cout << std::endl;
         }
      

      这篇关于班级成员初始化程序在VS 2013中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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