Skip to content

Barton–Nackman trick

More C++ Idioms/Barton-Nackman trick

Intent

Support overloaded operators without relying on namespaces or function template overload resolution.

Motivation

template<typename T>
class List {
   // ...
};
template<typename T>
bool operator==(List<T> const & lft, List<T> const & rgt) {
   //...
}

Solution and Sample Code

template<typename T>
class List {
 public:
    friend bool operator==(const List<T> & lft,
                           const List<T> & rgt) {
        // ...
    }
};
template<typename T>
class EqualityComparable {
public:
    friend bool operator==(const T & lft, const T & rgt) { return lft.equalTo(rgt); }
    friend bool operator!=(const T & lft, const T & rgt) { return !lft.equalTo(rgt); }
};

class ValueType :
    private EqualityComparable<ValueType> {
 public:
    bool equalTo(const ValueType & other) const;
};

Known Uses

Boost.Operators library

Related Idioms

Curiously Recurring Template Pattern

Wikipedia Barton-Nackman trick

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0777.pdf