Template不能推导返回值

侯捷的《STL源码剖析》中提到“template参数推导机制”推而导之的只是参数,而无法推导函数的返回值类型,其意思是这样的:

#include <iostream>

using namespace std;

template <typename I , typename T ,typename W>

W Add(I a, T b)

{

W c = a + *b;

return c;

}

void main()

{

int a = 3;

int b = 4;

int c;

int d = Add(a, &b );

cout<<d<<endl;

}

编译出现错误提示: error C2783: 'W __cdecl Add(I,T)' : could not deduce template argument for 'W'

而如果程序写成如下,则编译通过:

#include <iostream>

using namespace std;

template <typename I , typename T ,typename W>

W Add(I a, T b,W d) //区别在此处

{

W c = a + *b;

return c;

}

void main()

{

int a = 3;

int b = 4;

int c = 5;

int d = Add(a, &b ,c);                 //调用函数Add时指明了第三个参数 类型,因此编译器可以推导出返回值的类型

cout<<d<<endl;

}

侯捷提到可以用内嵌型别的方法解决,书中示例如下(为了能编译有改动):

#include <iostream>

using namespace std;

template <typename T>

struct MyIter{

typedef  T  value_type;                               //声明内嵌类型

T* ptr;

MyIter(T* p=0) : ptr(p){}

T& operator*() const {return *ptr;}                //重载*操作符

};

template<typename  I>

typename  I::value_type fun( I ite )                //使用其作为函数返回值,根据 参数推导出返回值的实际类型

{

return *ite;

}

void main()

{

MyIter<int>    ite(new int(8)) ;

cout<<fun(ite);

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值