C++11 decltype 和auto

C++ decltype 自动推导类型
摘自 cppreference

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)写法
完美转发的forward函数

//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); };  
  



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值