执行 Herb 建议的正常方式如下:
struct A {
A& operator+=(cosnt A& rhs)
{
...
return *this;
}
friend A operator+(A lhs, cosnt A& rhs)
{
return lhs += rhs;
}
};
将此扩展到 CRTP:
template <typename Derived>
struct Base
{
Derived& operator+=(const Derived& other)
{
//....
return *self();
}
friend Derived operator+(Derived left, const Derived& other)
{
return left += other;
}
private:
Derived* self() {return static_cast<Derived*>(this);}
};
如果你试图避免使用friend
这里,你会发现它几乎是这样的:
template<class T>
T operator+(T left, const T& right)
{return left += right;}
但仅对派生自 的事物有效Base<T>
,这样做既棘手又丑陋。
template<class T, class valid=typename std::enable_if<std::is_base_of<Base<T>,T>::value,T>::type>
T operator+(T left, const T& right)
{return left+=right;}
此外,如果它是friend
类的内部,那么它在技术上不在全局命名空间中。a+b
因此,如果有人在两者都不是 a 的地方写了一个 invalid Base
,那么您的重载将不会导致 1000 行错误消息。免费的类型特征版本可以。
至于为什么要签名:可变的值,不可变的 const&。&& 仅适用于移动构造函数和其他一些特殊情况。
T operator+(T&&, T) //left side can't bind to lvalues, unnecessary copy of right hand side ALWAYS
T operator+(T&&, T&&) //neither left nor right can bind to lvalues
T operator+(T&&, const T&) //left side can't bind to lvalues
T operator+(const T&, T) //unnecessary copies of left sometimes and right ALWAYS
T operator+(const T&, T&&) //unnecessary copy of left sometimes and right cant bind to rvalues
T operator+(const T&, const T&) //unnecessary copy of left sometimes
T operator+(T, T) //unnecessary copy of right hand side ALWAYS
T operator+(T, T&&) //right side cant bind to lvalues
T operator+(T, const T&) //good
//when implemented as a member, it acts as if the lhs is of type `T`.
如果移动比副本快得多,并且您正在处理交换运算符,那么您可能有理由重载这四个。但是,它仅适用于交换运算符(其中 A?B==B?A,所以 + 和 *,但不适用 -、/ 或 %)。对于非交换运算符,没有理由不使用上面的单个重载。
T operator+(T&& lhs , const T& rhs) {return lhs+=rhs;}
T operator+(T&& lhs , T&& rhs) {return lhs+=rhs;} //no purpose except resolving ambiguity
T operator+(const T& lhs , const T& rhs) {return T(lhs)+=rhs;} //no purpose except resolving ambiguity
T operator+(const T& lhs, T&& rhs) {return rhs+=lhs;} //THIS ONE GIVES THE PERFORMANCE BOOST