I am wondering about the following warning of the clang compiler when I pass an integer
to an std::initializer_list< size_t >
:
non-constant-expression cannot be narrowed from type 'int' to 'unsigned long' in initializer list
Why can int
be casted to a size_t
but an int
not be passed to an std::initializer_list< size_t >
, i.e.
int main()
{
size_t s_t = 0;
int i = 0;
std::initializer_list<size_t> i_l = { i }; // warning
s_t = i; // no warning
return 0;
}
You have run afoul of [dcl.init.list]/7
Since
i
is not a constant expression this counts as a narrowing conversion and narrowing conversions are not allowed in initializer list. If you were to useThen it would not narrow even though
0
is anint
since the compiler knows0
can be represented in each type.