Why must <initializer_list> be enabled to use auto?
There is already a similar question in SO, but I want to emphasize another aspect of the init-lists partition. Consider the following:
auto x = {1}; //(1) This is poorly formed (8.5.4 / 2) unless the <initializer_list> header is included. But why? The standard states that the std::initializer_list template is not predefined. Does this mean that declaration (1) introduces a new type? In all other situations where auto can be used, for example,
auto y = expr; where expr is an expression, type aut deduces already exists. On the other hand, from a logical point of view, the compiler should assign an implicite type to the {1} construct, for which std::initializer_list is a different name. But in the declaration (1) we do not want to name this type. So why this header should be included. A similar situation with nullptr . Its type exists implicitly, but to specify it explicitly you must include <cstddef> .
This is not the same. The rules for std::nullptr_t and std::initializer_list are actually different.
std::nullptr_t is just a typedef for an inline type. His definition
namespace std { using nullptr_t = decltype(nullptr); } The type exists if you include the header or not.
std::initializer_list is a class template, not a predefined type. It really does not exist unless you include a header that defines it. In particular, the initializer list { 1 } not of type std::initializer_list<int> ; he has no type at all, because it is not an expression. (Initializer lists are special syntax constructs and cannot appear anywhere an expression can be.)
std::initializer_list just a little special. First, there are special initialization rules std::initializer_list from the syntax of the initializer list (select the array and refer to the object). However, this requires the definition of std::initializer_list .
The second special case is a deduction of type auto . There is a special rule here. But again, this does not mean that the compiler will automatically detect the type; it just means that he finds out.