decltype 操作符可以得到一个表达式的类型,比如可以如下使用:double x(100.0);
int n(5);
decltype(x*n) result(x*n); 最后一条语句指定了 result 这个变量的类型是 x*n 这个表达式的类型,即 double 类型。这只是一个示例,实际上 decltype 操作符多用于函数模板 。偶尔,具有多个类型形参的模板函数的返回类型可能取决与模板实例化时所用的类型。比如一个模板函数,它返回的是类型不同的两个数组的对应元素的乘积,因此返回结果的类型取决于数组实参的实际类型,故而无法指定一个具体的返回类型。下面代码测试了这一种情况:
[C++] 纯文本查看 复制代码
#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
template<class T1, class T2>
auto product(T1 v1[], T2 v2[], size_t count)->decltype(v1[0]*v2[0])
{
decltype(v1[0]*v2[0]) sum(0);
for(size_t i = 0; i<count; i++) sum += v1[i]*v2[i];
return sum;
}
int main()
{
double x[] = {100.5, 99.5, 88.7, 77.8};
short y[] = {3, 4, 5, 6};
long z[] = {11L, 12L, 13L, 14L};
size_t n = 4;
cout << "Result type is "<< typeid(product(x, y, n)).name() << endl;
cout << "Result is " << product(x, y, n) << endl;
cout << "Result type is "<< typeid(product(z, y, n)).name() << endl;
cout << "Result is " << product(z, y, n) << endl;
return 0;
}
输出:Result type is double
Result is 1609.8
Result type is long
Result is 230 在上面的程序中,模板函数的返回类型由关键字 auto 来指定,实际的返回类型则是在创建模板实例时由编译器确定的。
->decltype(v1[0]*v2[0]) 这部分确定了任何模板实例返回的类型。
在程序中,我们还使用了 typeid 操作符,因此需要包含一个 typeinfo 头文件。
从输出的结果可以看到,当前两个参数分别是 double 和 short 类型数组时,product() 函数实例的返回值类型是 double 类型,事实也应该确实如此;同样,当两个实参分别为 short 和 long 类型数组时,product() 函数返回的是 long 类型。 |