Implementing brace-enclosed initializer lists in a custom C++ standard library

1 week ago 10
ARTICLE AD BOX

std::initializer_list is implemented with the compiler. You need to coordinate with the compiler.

For example:

GCC requires initializer_list<E> has two members, the first of type const E* and the second of type std::size_t, and a constructor that takes a const E* and std::size_t (which you should simply copy to the members). The first pointer is the pointer to the beginning of the temporary array and the second to the size of the temporary array. (The temporary is generated by the compiler).

Clang requires initializer_list<E> has two members, the first of type const E* and the second either of type const E* or std::size_t. It does not require it to have any constructors, the fields are directly initialized. The first field is a pointer to the beginning of the temporary array and the second is either a pointer to the end or the size.

MSVC does not require anything about the layout of initializer_list<E>, only that it has a constructor that takes two const E* pointers. These will be pointers to the beginning and end of the temporary array.

Other compilers will have different requirements but consult whatever compiler you are targetting with your standard library.

This implementation will generally work with Clang, MSVC, and GCC, and probably other compilers:

namespace std { template<typename _E> struct initializer_list { private: const _E* __begin = nullptr; std::size_t __size = 0; constexpr initializer_list(const _E* __begin, std::size_t __size) noexcept : __begin(__begin), __size(__size) {} public: // MSVC requires public constructor constexpr initializer_list(const _E* __begin, const _E* __end) noexcept : __begin(__begin), __size(__end - __begin) {} public: // public interface, like value_type, default constructor, size, begin, end, etc. }; }

Also the compiler is special casing initializers with { ... } braces when the type being constructed is a specialisation of std::initializer_list, which is how it achieves it's behaviour.

Read Entire Article