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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With