曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 2784|回复: 0
打印 上一主题 下一主题

decltype 操作符

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2013-7-7 17:09:32 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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 类型。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-3 23:30 , Processed in 0.083666 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表