而编译时类型推导,除了我们说过的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();
}