【问题标题】:Purpose of decltype-specifier [duplicate]decltype-specifier 的用途
【发布时间】:2014-06-02 03:26:18
【问题描述】:

我正在阅读关于限定名称查找的条款。里面有一段话:

如果嵌套名称说明符中的 :: 范围解析运算符不是 前面有一个 decltype 说明符,查找该名称之前的名称 :: 仅考虑其特化的名称空间、类型和模板 是类型。

标准中定义的decltype-specifier是:

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

这是什么意思?您能解释一下该关键字的用途吗?

【问题讨论】:

  • 阅读this article。作者专注于 decltypeauto 之间的区别,但它仍然是一本引人入胜的读物,并提供了对两者功能的洞察。

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


【解决方案1】:

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

【讨论】:

  • 感谢您的明确答复。但我仍然不明白 decltype-specifier 如何影响限定名称查找。你能举个例子吗?
  • 当然,我添加了一个编辑,显示了范围运算符的示例
猜你喜欢
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
相关资源
最近更新 更多