Type Deduce - Decltype in C++

Declared Type

decltype 是在 C++11 引入的关键字,用来推导 entity 或者 expression 的类型。它允许在编译时获取表达式的静态类型,用该类型声明变量、定义函数返回类型等。当需要保留引用、CV qualifier 等修饰符时,decltype 提供精确的类型推导。

一个简单的例子,下面是如何推导变量类型:

int a = 10; // 'a' is an int type variable
decltype(a) b = 20; // 'b' has the same type as 'a'

const int c_a = 10; // 'c_a' is a const int type variable
decltype(c_a) c_b = 20; // 'c_b' has the same type as 'c_a'

下面是推导表达式类型的例子:

int a = 10;
double b = 3.14;
decltype(a + b) c = a + b;

Return Type Deduction

decltype 还能显性的指示函数的返回值,使用 decltype 配合 auto 将返回类型后置,被称为 trailing return type 。同样的,函数的返回类型将在编译时推导出来。这种写法尤其适合泛型编程。

template<typename T, typename U>
auto add(T a, U b) -> decltype(a + b) {
    return a + b;
}
template<typename T, typename U>
auto add(T a, U b) { // C++14
    return a + b;
}

实际上,自 C++14,auto 也可以用于推导返回类型,那要 decltype 有什么好处呢?我们现在可以明确的好处有:declytpe 会保留所有的修饰符,而 auto 会忽略掉引用和 const

decltype(auto)

使用 decltype(auto) 推导变量类型会保留引用、const 等修饰符。

#include <type_traits>

const int& getVal();

int main(){
	auto i = getVal(); // i is deduced as int type
	static_assert(std::is_same_v<decltype(i), int>)
	
	decltype(auto) j = getVal(); // j is deduced as const int& type
	static_assert(std::is_same_v<decltype(j), const int&>)
	return 0;
}

使用 decltype(auto) 推导表达式不需要尾置返回类型:

#include <type_traits>

decltype(auto) getVal(){

}

int main(){

	return 0;
}