【Effective Modern C++】第一章 类型推导:3. 理解 decltype

个人认为原著写的非常晦涩难懂,所以精简如下:

decltype用于告知名字或表达式的类型:

c++ 复制代码
const int i = 0;               // decltype(i) 是 const int

bool f(const Widget& w);       // decltype(w) 是 const Widget&;decltype(f) 是 bool(const Widget&)

struct Point {
  int x, y;
};                             // decltype(Point::x) 是 int;decltype(Point::y) 是 int

Widget w;                      // decltype(w) 是 Widget

if (f(w)) ...                  // decltype(f(w)) 是 bool

template<typename T>           // std::vector 的简化版
class vector {
public:
  ...
  T& operator[](std::size_t index);
  ...
};

vector<int> v;
...
if (v[0] == 0) ...             // decltype(v[0]) 是 int&

使用场景:当函数的返回类型依赖于参数类型时:我们不知道用户会传什么容器进来

c++ 复制代码
// C++11的写法(尾置返回类型)
template<typename Container, typename Index>
auto authAndAccess(Container& c, Index i)
    -> decltype(c[i])  // 告诉编译器:返回类型就是c[i]的类型
{
    return c[i];
}

// C++14的写法更简洁
template<typename Container, typename Index>
decltype(auto) authAndAccess(Container& c, Index i)
{
    return c[i];  // 编译器自动推导返回类型
}

我们希望这个函数返回容器元素,类型要和容器[]操作符返回的一致。但不同的容器,operator[]返回的类型可能不同:

  • vector<int>operator[]返回int&
  • vector<bool>operator[]返回一个特殊对象

auto的区别auto会去掉引用,decltype原样返回表达式的类型(引用/const会保留)。

decltype(auto):这是C++14的特性,意思是:

  • auto来自动类型推导
  • 但用decltype的规则来推导(保留引用)
    可以理解为 保留引用/const的auto

一个小陷阱

c++ 复制代码
// 括号的微妙影响
int x = 0;
decltype(x) a = x;     // int
decltype((x)) b = x;   // int&

总结

  • 绝大多数情况下,decltype会得出变量或表达式的类型而不作任何修改。
  • 对于类型为 T 的左值表达式,除非该表达式仅有一个名字, decltype 总是得出类型 T&
  • C++14 支持 decltype(auto) ,和 auto 一样,它会从其初始化表达式出发来。

原著在线阅读地址

相关推荐
li16709027021 分钟前
第二十七章:智能指针
c语言·数据结构·c++·visual studio
王老师青少年编程1 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【贪心与二分判定】:数列分段 Section II
c++·算法·贪心·csp·信奥赛·二分判定·数列分段 section ii
zh_xuan1 小时前
libcurl调用https接口
c++·libcurl
就叫飞六吧1 小时前
QT写一个桌面程序exe并动态打包基本流程(c++)
开发语言·c++
蜡笔小马1 小时前
1.c++设计模式-工厂模式
c++
汉克老师2 小时前
GESP2025年3月认证C++五级( 第三部分编程题(2、原根判断))
c++·算法·模运算·gesp5级·gesp五级·原根·分解质因数
winner88812 小时前
从零吃透C++命名空间、std、#include、string、vector
java·开发语言·c++
AI进化营-智能译站2 小时前
ROS2 C++开发系列07-高效构建机器人决策逻辑,运算符与控制流实战
开发语言·c++·ai·机器人
winner88812 小时前
C++ 命名空间、虚函数、抽象类、protected 权限全套通俗易懂精讲(附与 Java 对比)
java·开发语言·c++
不会编程的懒洋洋3 小时前
C# P/Invoke 基础
开发语言·c++·笔记·安全·机器学习·c#·p/invoke