我正在阅读关于限定名称查找的条款。其中有一段引用:
如果嵌套名称说明符中的 :: 作用域分辨符没有在一个 decltype 说明符之前,那么在 :: 之前的名称的查找只考虑命名空间、类型以及其特化为类型的模板。
按照标准中的定义,decltype 说明符
是:
decltype-specifier:
decltype ( expression )
decltype ( auto )
通过这个关键字的意思是什么?你能解释一下这个关键字的作用吗?
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
至于第二个类型说明符版本,它将在C++14中允许,使一些繁琐的decltype
声明更易于阅读:
decltype(longAndComplexInitializingExpression) var = longAndComplexInitializingExpression; // C++11
decltype(auto) var = longAndComplexInitializingExpression; // C++14
编辑:
decltype
可以自然地与作用域运算符一起使用。
以下是来自这篇现有文章的示例:
struct Foo { static const int i = 9; };
Foo f;
int x = decltype(f)::i;
您引用的标准规定,在这种情况下,对于 decltype(f)
的名称查找不仅考虑命名空间、类型和模板及其类型的特化。这是因为在此情况下,名称查找被转移到 decltype
运算符本身。
decltype
和auto
之间的区别,但它仍然是一篇引人入胜的文章,并提供了对两者功能的洞察。 - Praetorian