Question

What is preferable (if any)?

Variant 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)  //...
};

Variant 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); }
Was it helpful?

Solution

I'd prefer to use Boost.Operators mentioned by @SteveJessop in the comments, which formalizes and automates your first approach. They also take care of the empty base optimization if you happen to need multiple sets of operators (and hence would need multiple inheritance). It's not so much the savings in typing, but also the code documentation/enforcement value, since these bases classes are right at the front of the class interface. In that sense, it's a primitive way of Concepts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top