侯捷的《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);
}