#include <initializer_list>
using namespace std;
template<class T>
void f(initializer_list<T>)
{}
int main()
{
typeid(1); // OK
typeid(int); // OK
typeid(decltype(1)); // OK
f({1, 2}); // OK
typeid({1, 2}); // error
decltype({1, 2}) v; // error
typeid(decltype({1, 2})); // error
}
Is {1, 2} a value?
If yes, why is typeid({1, 2}); not legal?
If no, why can it be assigned to an initializer_list object?
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.
An initializer specifies the initial value of a variable. You can initialize variables in these contexts: In the definition of a variable: C++ Copy. int i = 3; Point p1{ 1, 2 };
Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.
No, it is a syntactic construct with no intrinsic value. It's not even (syntactically) an expression. But it can be used to initialize an object.
The typeid
operator requires a proper expression, but function arguments do not. When you pass a function argument, you are actually initializing the parameter object.
initializer_list
can be initialized by such a thing. Arrays can also be initialized by braced initializer lists. The list is used to initialize an array accessed through the initializer_list
.
Confusingly, auto x = { 1, 2, 3 };
causes x
to be declared as an std::initializer_list< int >
. This is a special exception where auto
differs from decltype
, and it has been proposed for deprecation. There are few good uses for persistent initializer_list
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With