C++ decltype 自动推导类型
int var;
const int&& fx();
struct A { double x; }
const A* a = new A();
decltype(fx()); const int&&
对 左值引用 的const int。
decltype(var); int
变量 var 的类型。
decltype(a->x); double
成员访问的类型。
decltype((a->x)); const double&
内部括号导致语句作为表达式而不是成员访问计算。 由于 a 声明为 const 指针,因此类型是对 const double 的引用。
##################################################################
其中decltype 和 auto 连在一起用到的比较多 下边是参考 cppreference的列子
#include <iostream>
struct A { double x; };
const A* a = new A{ 0 };
decltype(a->x) y; // y的类型是double(声明类型)
decltype((a->x)) z = y; // z的类型是const double&(左值表达式)
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u); // 返回类型依赖于模板参数
template<typename T,typename U>
int main()
{
int i = 33;
decltype(i) j = i * 2;
std::cout << "i = " << i << ", "
<< "j = " << j << '\n';
auto f = [](int a, int b) -> int
{
return a * b;
};
decltype(f) g = f; // lambda的类型是唯一且无名的
i = f(2, 2);
j = g(3, 3);
std::cout << "i = " << i << ", "
<< "j = " << j << '\n';
}
decltype和 auto区别
auto从变量值推出类型
decltype从表达式推出类型 比如decltype(fun());他并不执行fun();
我声明一个 int x=5;
int ref=&i;
auto(ref) 是根据5推导出来 类型为 int
而decltype(ref)推导出来为 int&
同理 const int x=5 auto(x)会漏掉const 的关键字 而decltype(x)则不会
--
------------------------------------------------------------------------------------------------------------------
decltype和auto用途-
比方 我想 decltype(fun()) a;
但不需要计算fun()这个函数 就 用decltype
auto a的话 需要有一个赋值auto a = fun(x); 这样 是计算fun(x)后得出来的
auto+decltype 可以进行动态推导
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u); // 返回类型依赖于模板参数
上文中这个函数就是一个最常用的例子
用模板 写一个返回值为一个 类型为 t+u的列子
--------------------------------------------------------------------------------------
C++14中 还支持了 decltype(auto)写法
//C++11
template<typename T, typename U>
auto myFunc(T&& t, U&& u) -> decltype (forward<T>(t) + forward<U>(u))
{ return forward<T>(t) + forward<U>(u); };
//C++14
template<typename T, typename U>
decltype(auto) myFunc(T&& t, U&& u)
{ return forward<T>(t) + forward<U>(u); };