我正在阅读有关限定名称查找的条款。那里引用了一句话:
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.
在标准decltype-specifier
中的定义是:
decltype-specifier:
decltype ( expression )
decltype ( auto )
这是什么意思?您能解释一下该关键字的用途吗?
decltype
是 C++11 引入的新关键字之一。 它是一个返回表达式类型的说明符。
在模板编程中检索依赖于模板参数或返回类型的表达式类型特别有用。
示例来自 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
至于第二个说明符版本,在 C++14 中将允许它使一些繁琐的 decltype
声明更易于阅读:
decltype(longAndComplexInitializingExpression) var = longAndComplexInitializingExpression; // C++11
decltype(auto) var = longAndComplexInitializingExpression; // C++14
编辑:
decltype
自然可以与作用域运算符一起使用。
示例来自 this existing post :
struct Foo { static const int i = 9; };
Foo f;
int x = decltype(f)::i;
您对标准的引用指定,在这种情况下,decltype(f)
名称的查找不仅仅考虑命名空间、类型和专门化为类型的模板。这是因为在这种情况下,名称查找被转移到 decltype
运算符本身。