Why is there no narrowing of the conversion in this code, which leads to an error?

g++with -std=c++11seems 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 comment line should be erroneous, but it is not.

Update

Thanks to Jesse for pointing out the standard (8.5.4 p7) which determines why this is normal. Here is an example of code that helps 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 just presented will help others avoid some narrowing problems when using initialization lists.

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

+5
source share
2 answers

The rules are given in 8.5.4 p7, which excludes your example.

, , , & hellip;

( )

+10

, , , float.

, g++, , , float:

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

All Articles