Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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.

like image 295
Michael Goldshteyn Avatar asked Mar 08 '13 15:03

Michael Goldshteyn


1 Answers

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)

like image 192
Jesse Good Avatar answered Sep 27 '22 22:09

Jesse Good