简体   繁体   中英

Why is there no narrowing conversion in this code, resulting in an error?

g++ with -std=c++11 seems to accept it:

#include <vector>
#include <initializer_list>

std::vector<float> vf={1,2,3}; // Isn't this narrowing (i.e., an error)?

int main() {}

It would seem that the line with the comment should error out, but it does not.

Update

Thanks to Jesse for pointing to the standardese (8.5.4 p7) that defines why this is OK. Here is some sample code that helps to clarify the behavior defined by the standard:

const int v5=5;
int v6=6;

vector<double> vd1={1,2,3,4};       // OK
vector<double> vd2={1,2,3,4,v5};    // Still OK, v5 is const
vector<double> vd3={1,2,3,4,v5,v6}; // Error, narrowing conversion, because v6 
                                    // is non-const
vector<double> vd4={1,2,3,4,v5,static_cast<const int>(v6)}; // Also errors on 
                                    // gcc 4.7.2, not sure why.

I hope that the examples I just presented will help others to get past some narrowing issues when using initializer lists.

If anyone knows why the last case violates the standard definition, please post a comment.

The rules are in 8.5.4 p7 which excludes your example

from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type , or …

(emphasis mine)

I don't see why this should error out given that all three integers can be exactly represented as float .

That said, I can get g++ to give me a warning if I include a constant that doesn't fit in a float :

warning: narrowing conversion of '2112112112' from 'int' to 'float' inside { } [-Wnarrowing]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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