Why isn't std::initializer_list
a core-language built-in?
It seems to me that it's quite an important feature of C++11 and yet it doesn't have its own reserved keyword (or something alike).
Instead, initializer_list
it's just a template class from the standard library that has a special, implicit mapping from the new braced-init-list {...}
syntax that's handled by the compiler.
At first thought, this solution is quite hacky.
Is this the way new additions to the C++ language will be now implemented: by implicit roles of some template classes and not by the core language?
Please consider these examples:
widget<int> w = {1,2,3}; //this is how we want to use a class
why was a new class chosen:
widget( std::initializer_list<T> init )
instead of using something similar to any of these ideas:
widget( T[] init, int length ) // (1)
widget( T... init ) // (2)
widget( std::vector<T> init ) // (3)
- a classic array, you could probably add
const
here and there - three dots already exist in the language (var-args, now variadic templates), why not re-use the syntax (and make it feel built-in)
- just an existing container, could add
const
and&
All of them are already a part of the language. I only wrote my 3 first ideas, I am sure that there are many other approaches.
std::array
but not withstd::initializer_list
? They have different semantics, so that wouldn't work. – Insurablestd::array<T>
is no more 'part of the language' thanstd::initializer_list<T>
. And these are not nearly the only library components that the language relies on. Seenew
/delete
,type_info
, various exception types,size_t
, etc. – Diazoleconst T(*)[N]
, because that behaves very similarly to howstd::initializer_list
works. – Ruttgerstd::array
or a statically-sized array are less desirable alternatives. – Chiliarch