I want to make a small library of my own containers without relying on STL at all, as a form of exercise. How can I define an initializer list constructor for my classes without std::initializer_list? How is it even implemented?
1 Answer
How can I define an initializer list constructor for my classes without
std::initializer_list?
You don't. The very definition of "initializer list constructor" is tied into std::initializer_list. Just like the result of typeid is tied directly into std::type_info, and the result of sizeof and alignof is a std::size_t.
Attempting to use C++ while pretending the standard library in its entirety does not exist is folly. There are parts of it you can ignore without consequence, but if you want to have an "initializer list constructor", you have to use std::initializer_list.
The C++ standard library is not optional; it is not divorced from C++ as a langauge. Parts of it are, but std::initializer_list isn't one of those parts.
7 Comments
initalizer_list instead of reusing std::vector or std::array? Something like { 1, 2, 3 } means std::vector<int> which contains 1, 2 and 3?std::vector<int> implies dynamic allocation, and std::array<int, 3> ties the number of elements into the type. std::initalizer_list is a temporary with unspecified sizestd::initializer_list is just a pair of pointers. The temporary it refers to is a temporary.
std::vectorcouldn't, you can't do it general case either. There is a reason whystd::initializer_listexists.{ stuff }doesn't actually have a type. It takes the compiler to do some "magic" to turn that braced-init-list into astd::initializer_list. You would have to make your own compiler to provide your own "magic".<initializer_list>is guaranteed to be available on freestanding implementations, so there is no reason to avoid it.