【发布时间】:2012-02-11 23:41:08
【问题描述】:
我想知道为什么隐式类型转换不适用于类模板上的外部运算符重载。这是工作的非模板版本:
class foo
{
public:
foo() = default;
foo(int that)
{}
foo& operator +=(foo rhs)
{
return *this;
}
};
foo operator +(foo lhs, foo rhs)
{
lhs += rhs;
return lhs;
}
正如预期的那样,以下行编译正确:
foo f, g;
f = f + g; // OK
f += 5; // OK
f = f + 5; // OK
f = 5 + f; // OK
另一方面,当 foo 类被声明为这样的简单模板时:
template< typename T >
class foo
{
public:
foo() = default;
foo(int that)
{}
foo& operator +=(foo rhs)
{
return *this;
}
};
template< typename T >
foo< T > operator +(foo< T > lhs, foo< T > rhs)
{
lhs += rhs;
return lhs;
}
以下行编译错误:
foo< int > f, g;
f = f + g; // OK
f += 5; // OK
f = f + 5; // Error (no match for operator+)
f = 5 + f; // Error (no match for operator+)
我想了解为什么编译器 (GCC 4.6.2) 无法使用类模板版本的转换构造函数执行隐式类型转换。这是预期的行为吗?除了手动创建所有必要的重载之外,还有什么解决方法吗?
【问题讨论】:
-
你可以为 T 添加一个重载: foo operator +(foo lhs, T rhs)
标签: c++ templates operator-overloading implicit-conversion