Joh*_*hnB 5 c++ operator-overloading template-meta-programming c++-concepts
什么是可取的(如果有的话)?
变种A(Barton-Nackman):
template<class T>
struct equal_comparable {
friend bool operator == (const T & t1, const T & t2) {
return t1.equalTo (t2);
}
};
class MyClass : private equal_comparable<MyClass> {
bool equalTo (const MyClass & other) //...
};
Run Code Online (Sandbox Code Playgroud)
变体B(std :: enable_if):
struct MyClass {
static const bool use_my_equal = true;
bool equalTo (const MyClass & other) //...
};
template<class T>
typename std::enable_if<
T::use_my_equal,
bool
>::type
operator == (const T & t1, const T & t2) { return t1.equalTo (t2); }
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用@SteveJessop 在评论中提到的Boost.Operators ,它可以形式化并自动化您的第一种方法。如果您碰巧需要多组运算符(因此需要多重继承),它们还会处理空基优化。与其说是节省了输入,还不如说是代码文档/执行价值,因为这些基类位于类接口的前面。从这个意义上说,这是一种原始的 Concepts 方式。