In-class member initializer fails with VS 2013

醉酒当歌 提交于 2019-12-10 18:26:19

问题


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 compile fails with:

'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" };

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?


回答1:


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

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

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


来源:https://stackoverflow.com/questions/24518192/in-class-member-initializer-fails-with-vs-2013

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!