我有一个定义子类型的模板类。我试图将二进制operator+
定义为模板函数,但编译器无法解析operator+
的模板版本。运算符+用于模板类的子类型
#include <iostream>
template<typename other_type>
struct c {
c(other_type v) : cs(v) {}
struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs;
};
template<typename other_type>
typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left,
const typename c<other_type>::subtype& right)
{ return typename c<other_type>::subtype(left.val + right.val); }
// This one works
// c<int>::subtype operator+(const c<int>::subtype& left,
// const c<int>::subtype& right)
// { return c<int>::subtype(left.val + right.val); }
int main()
{
c<int> c1 = 1;
c<int> c2 = 2;
c<int>::subtype cs3 = c1.cs + c2.cs;
std::cerr << cs3.val << std::endl;
}
我想原因是因为所以它的查找operator+<int>
,而不是operator+
编译器(G ++ 4.3)无法猜测的模板类型。
这是什么原因?你能提出什么优雅的解决方案?
的原因是你已经按照C++标准14.8.2.4/4这里nondeduced上下文。 – 2010-05-05 20:21:25