最烦人的解析会阻止类中初始化std :: vector< int>。 [英] most vexing parse prevents in-class initializing a std::vector<int>
问题描述
C ++ 11允许类内初始化:
C++11 allows in-class initialization:
struct Foo{
std::vector<std::string> v{3}; // vector of 3 empty strings
};
如果我们想在类中初始化 ints 的向量,我们会得到其他结果:
If we wanted to initialize in-class a vector of ints, we would get something else:
struct Foo{
std::vector<int> v{3}; // vector of one element with value 3
};
此问题似乎是语言的局限性,。但是,如果这不是类内初始化,则可以使用括号代替大括号,并获得所需的结果:
This issue seems to be a limitation of the language, as discussed in previous questions. However, if this were not an in-class initialization, we would be able to use parentheses instead of braces, and get the desired result:
std::vector<int> v(3); // vector of three zeros
但是,由于最令人讨厌的解析:
struct Foo{
std::vector<int> v(3); // most vexing parse; doesn't compile
};
当然,上面的代码是否是好的设计实践尚有争议,因为我们可以轻松地移动我们正在尝试做一个构造函数。但是暂时将其搁置一旁,是否有一种方法可以执行所需的初始化,尽可能接近第一个 std :: string
示例,该示例可以正常工作?
Of course, it's debatable whether the code above is good design practice, since we can easily just move what we're trying to do into a constructor. But temporarily putting that aside, is there a way to perform the desired initialization, as closely as possible to the first std::string
example, which works with no problem?
推荐答案
默认成员初始化程序也可以与 =
一起使用。因此
Default member initializers work with =
as well. So
struct Foo{
std::vector<int> v = std::vector<int>(3);
};
会做到这一点。尽管很明显,一个主要警告是我们在这里重复了类型名称。
Will do it. Though obviously, a major caveat is the fact that we are repeating the type name here.
我们可以使用 decltype $ c来缓解它。 $ c>:
struct Foo{
std::vector<int> v = decltype(v)(3);
};
但这仍然让我们命名两次。
But that still has us naming things twice.
这篇关于最烦人的解析会阻止类中初始化std :: vector< int>。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!