Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is {1, 2} a value? If yes, what is its type? If no, why can it be assigned to an initializer list?

#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?

like image 463
xmllmx Avatar asked Sep 14 '13 03:09

xmllmx


People also ask

What is an initializer list used for?

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.

Why should initializer lists be used rather than assigning member variables values in the constructor body?

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.

What's an initializer in C++?

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 };

What is a member initializer?

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.


1 Answers

  1. 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.

  2. 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_lists.

like image 111
Potatoswatter Avatar answered Oct 16 '22 19:10

Potatoswatter