With the a function taking std::initializer_list as argument like shown below
int sumOf(std::initializer_list<int> numbers) {
int sum = 0;
for (auto x : numbers) {
sum += x;
}
return sum;
}
This code works
auto sum = sumOf({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
but not this
int i[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto x = sumOf(i);
Why does the second form not work? Or am I doing something wrong?
Edit:
From the gcc 4.7.2 implementation of std::intializer_list, the constructor of intializer_list is private and compiler needs to pass the size of the array.
// The compiler can call a private constructor.
constexpr initializer_list(const_iterator __a, size_type __l)
: _M_array(__a), _M_len(__l) { }
I guess the compiler cannot judge the size of the array from the variable "i" in certain cases. If so, passing static array to intializer_list cannot be supported by the compiler (?).
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }really created astd::initializer_list.auto i = { ... };, not sure if this works, though.auto i = { ... };but "i" seems to be no more behaving as an int array.std::initializer_list, which is the type expected by the function, and which is totally different from an array.