Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Barton-Nackman vs std::enable_if

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); }
like image 627
JohnB Avatar asked Oct 06 '22 18:10

JohnB


1 Answers

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.

like image 151
TemplateRex Avatar answered Oct 10 '22 04:10

TemplateRex