使用VS 2013,类内成员初始化程序失败

acr*_*075 3 c++ initializer-list visual-c++ c++11 visual-studio-2013

我期望编译以下代码,但Visual Studio 2013 Update 2给了我一个错误,而g ++ 4.7编译它很好.

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

struct Settings
{
    vector<string> allowable = { "-t", "--type", "-v", "--verbosity" };
};
Run Code Online (Sandbox Code Playgroud)

VS 2013编译失败:

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

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

vector<string> allowable = vector<string> { "-t", "--type", "-v", "--verbosity" };
Run Code Online (Sandbox Code Playgroud)

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

101*_*010 6

  • 您展示的示例是完全有效的C++,但它不适用于VC++ 2013.

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

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


   #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;
   }
Run Code Online (Sandbox Code Playgroud)

  • 因为构造函数被称为使用括号而不是大括号,所以可以简单地使用第二组大括号来强制调用`initializer_list <>`构造函数.所以`std :: vector <std :: string> allowable = {{" - t"," - type"," - v","--verbosity"}};`是一个更简单的解决方法.+1用于查找Connect错误. (2认同)