问题
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 thestd::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