Is {1, 2} a value? If so, what is its type? If not, why can it be assigned to a list of initializers?

#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 so, why typeid ({1, 2}); not legal?

If not, why can it be assigned to the initializer_list object?

+6
source share
2 answers
  • No, this is a syntax without internal meaning. It is not even a (syntactic) expression. But it can be used to initialize the object.

    The typeid operator requires the correct expression, but the function arguments do not. When you pass an argument to a function, you are actually initializing the parameter object.

  • initializer_list can be initialized with such a thing. Arrays can also be initialized using copied initializer lists. The list is used to initialize the array accessible through initializer_list .

Confusingly, auto x = { 1, 2, 3 }; calls x to declare as std::initializer_list< int > . This is a special exception where auto is different from decltype and it has been suggested for obsolescence. There are several good uses for persistent initializer_list s.

+4
source

typeid expression required

Form here

The typeid expression is an lvalue expression that refers to a static object of the polymorphic type const std::type_info or some type derived from it.

Syntax: typeid (expression)

Checks expression expression

  • expression typeid evaluates the expression and then refers to the std::type_info , which represents the dynamic type of the expression.

  • If the expression is not a glvalue expression of a polymorphic type, typeid does not evaluate the expression, and the std::type_info object that it identifies is a static type of expression.

0
source

Source: https://habr.com/ru/post/953812/


All Articles