关于c++中的decltype的用法小计

而编译时类型推导,除了我们说过的auto关键字,还有本文的decltype。

decltype与auto关键字一样,用于进行编译时类型推导,不过它与auto还是有一些区别的。decltype的类型推导并不是像auto一样是从变量声明的初始化表达式获得变量的类型,而是总是以一个普通表达式作为参数,返回该表达式的类型,而且decltype并不会对表达式进行求值。

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"
#include<iostream>
using  namespace  std;

template<typename T, typename U>
auto mul(T a, U b) ->decltype(a* b)
{
    return  a* b;
}
//不采用auto 也是可以实现的 先把空指针0 转化为U*指针,解引用它 得到一个不存在的*(*U)0;类似得到一个 *(*Z)0。
template<typename U, typename Z>
decltype (*(U*)0 * *(Z*)0) mul_type2(U a, Z b)
{
    return  a*b;
}

//本地是VS2013 ,应该是 c++ 11 不识别如下的写法。 据说 c++ 14可以直接用
//template<typename T, typename U>
//auto mul(T a, U b)
//{
//    return  a* b;
//
//}



int _tmain(int argc, _TCHAR* argv[])
{
    cout << "10*20 " << mul(10, 20) << endl;
    cout << "10.0*20 " << mul_type2(10.0, 20) << endl;
    cout << "10.1*20.4 " << mul(10.1, 20.4) << endl;
    cout << "10.1*20.4 " << mul_type2(10.1, 20.4) << endl;

    cin.get();


}

参考






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值