Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of decltype-specifier [duplicate]

I'm reading the clause about qualified name lookup. There is a quote from thereout:

If a :: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types.

As defined in the standard decltype-specifier is:

decltype-specifier:
    decltype ( expression )
    decltype ( auto )

By what does it mean? Can you explain purpose of that keyword?

like image 744
St.Antario Avatar asked Jun 02 '14 03:06

St.Antario


1 Answers

decltype is one of the new keywords introduced with C++11. It is a specifier that returns the type of an expression.

It is particularly useful in template programming to retrieve the type of expressions that depends on template parameters or return types.

Examples from the documentation:

struct A {
   double x;
};
const A* a = new A{0};

decltype( a->x ) x3;       // type of x3 is double (declared type)
decltype((a->x)) x4 = x3;  // type of x4 is const double& (lvalue expression)

template <class T, class U>
auto add(T t, U u) -> decltype(t + u); // return type depends on template parameters

As for the second specifier version, it will be allowed in C++14 to make some tedious decltype declarations easier to read:

decltype(longAndComplexInitializingExpression) var = longAndComplexInitializingExpression;  // C++11

decltype(auto) var = longAndComplexInitializingExpression;  // C++14

Edit:

decltype can naturally be used with the scope operator.

Example from this existing post:

struct Foo { static const int i = 9; };

Foo f;
int x = decltype(f)::i;

Your quote of the standard specify that in that case, the lookup of the name for decltype(f) does not consider only namespaces, types, and templates whose specializations are types. This is because in this case, the name lookup is transferred to the decltype operator itself.

like image 73
quantdev Avatar answered Sep 21 '22 15:09

quantdev