decltype关键字

核心特性

  • 非求值上下文:不会对表达式进行实际求值
  • 精确类型推导:保留表达式的值类别(value category)和常量性

基本用法

推导表达式类型

1
2
int i = 4;
decltype(i) a; // 推导结果为int,a的类型为int

与类型别名合用

1
2
3
using size_t = decltype(sizeof(0));    // 获取sizeof操作的标准返回类型
using ptrdiff_t = decltype((int*)0 - (int*)0); // 指针差值类型
using nullptr_t = decltype(nullptr); // 空指针类型

重用匿名类型

1
2
3
4
5
6
struct {  // 匿名结构体
int d;
double b; // 修正拼写错误 doubel → double
} anon_s;

decltype(anon_s) as; // 复用匿名类型定义新变量

泛型编程(C++11起)

1
2
3
4
5
// 配合auto追踪函数返回类型(尾置返回类型)
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) {
return t + u;
}

💡 关键应用场景

  1. 元编程:配合SFINAE实现类型萃取
  2. 完美转发:保持值类别的decltype(auto)
  3. 接口适配:自动推导依赖其他类型的复杂返回类型
1
2
3
// 类型萃取示例
template<typename T>
using remove_reference_t = decltype(std::remove_reference<T>::type);

特殊情形处理

表达式类型 decltype推导规则 示例
变量名 变量声明类型 decltype(i) → int
左值表达式 T& decltype((i)) → int&
纯右值表达式 T decltype(1+2) → int
将亡值表达式 T&& decltype(std::move(i)) → int&&