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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…