c++ - decltype 说明符的用途

标签 c++ c++11 c++14 decltype

<分区>

我正在阅读有关限定名称查找的条款。那里引用了一句话:

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 运算符本身。

关于c++ - decltype 说明符的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23986932/

相关文章:

c++ - 使用 c++0x 初始化列表时出现段错误

c++ - 如何将真实类型的汽车传递给模板

c++ - 本地结构通过使用通用模板函数影响不同的翻译单元

c++ - Fortran 和 C++ 计算的值之间的差异

c++ - Qt中显示图像的正确方法

c++ - 多线程 unordered_map

带有嵌套对象优化的 c++ emplace_back

c++ - "variable"的定义是什么?

c++ - 将 libsodium.a 链接到共享对象时出错

c++ - Eigen 中的 move 语义