decltype-specifier的目的

St.*_*rio 8 c++ decltype c++11 c++14

我正在阅读关于限定名称查找的条款.引用来自:

如果嵌套名称说明符中的:: scope resolution运算符前面没有decltype-specifier,则查找此前面的名称::仅考虑其专门化为类型的名称空间,类型和模板.

根据标准的定义decltype-specifier是:

decltype-specifier:
    decltype ( expression )
    decltype ( auto )
Run Code Online (Sandbox Code Playgroud)

这是什么意思?你能解释一下这个关键词的用途吗?

qua*_*dev 11

decltype是C++ 11引入的新关键字之一.它是一个返回表达式类型的说明符.

它在模板编程中特别有用,可以检索依赖于模板参数或返回类型的表达式类型.

文档中的示例:

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
Run Code Online (Sandbox Code Playgroud)

对于第二个说明符版本,在C++ 14中允许使一些繁琐的decltype声明更容易阅读:

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

decltype(auto) var = longAndComplexInitializingExpression;  // C++14
Run Code Online (Sandbox Code Playgroud)

编辑:

decltype 可以自然地与范围运算符一起使用.

这个现有帖子的例子:

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

Foo f;
int x = decltype(f)::i;
Run Code Online (Sandbox Code Playgroud)

您对该标准的引用指定在这种情况下,名称的查找decltype(f)不仅考虑其特化是类型的名称空间,类型和模板.这是因为在这种情况下,名称查找将传输给decltype操作员本身.