简体   繁体   English

错误的std :: vector构造函数

[英]Wrong std::vector constructor

I'm getting a strange error from Clang when compiling what should be a straightforward line of code. 我在编译应该是一个简单的代码行时从Clang得到一个奇怪的错误。

This code produces an error: 此代码产生错误:

size_t s = 5;
std::vector<double> bestScores{s, -1.0};

I'm simply trying to use constructor #2 to fill a new vector with five -1.0 values. 我只是尝试使用构造函数#2来填充具有五个-1.0值的新向量。 The error I get is Non-constant expression cannot be narrowed from type 'size_type' (aka 'unsigned long') to 'double' in initializer list . 我得到的错误是非常量表达式不能从初始化列表中的类型'size_type'(又名'unsigned long')缩小到'double'

What is going on? 到底是怎么回事? This compiles fine: 编译好:

std::vector<double> bestScores{5, -1.0};

Is it trying to use the initializer list constructor? 它是否尝试使用初始化列表构造函数? I thought you needed two curly braces for that: 我认为你需要两个花括号:

std::vector<double> bestScores{{5, -1.0}};

The issue is that you are constructing the vector using a brace-enclosed initialization list. 问题是您使用括号括起的初始化列表构造向量。 That favours the std::initializer_list<T> constructor when applicable. 这适用于std::initializer_list<T>构造函数。 In this case, the size_t , -1.0 list is compatible with std::initializer_list<double> , so that constructor gets picked. 在这种情况下, size_t-1.0列表与std::initializer_list<double>兼容,因此构造函数被选中。 You need to use the old-style, C++03 construction: 您需要使用旧式的C ++ 03构造:

std::vector<double> bestScores(s, -1.0);

This is one of the gotchas of brace-enclosed initializers. 这是支撑封闭初始化器的问题之一。 They don't play well for certain standard library container instantiations. 它们不适合某些标准库容器实例化。 You have to remember that the std::initializer_list constructor will trump the others. 你必须记住std::initializer_list构造函数将胜过其他构造函数。

The issue is that when a class has an std::initializer_list constructor, it will prefer that when using the uniform initialization syntax if the arguments are convertible to the initializer_list's type ( double in this case). 问题是当一个类有一个std::initializer_list构造函数时,如果参数可以转换为initializer_list的类型(在这种情况下是double ),那么在使用统一初始化语法时它会更喜欢。 See a detailed answer at programmers.stackexchange.com . 请参阅programmers.stackexchange.com上的详细解答。

For now, your solution is to use the non-uniform syntax that uses parenthesis. 目前,您的解决方案是使用使用括号的非统一语法。 This means it won't consider the std::initializer_list constructor, and do what you want in this case. 这意味着它不会考虑std::initializer_list构造函数,并在这种情况下执行您想要的操作。

std::vector<double> bestScores(s, -1.0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM