Barton–Nackman trickBarton–Nackman trick is a term coined by the C++ standardization committee (ISO/IEC JTC1/SC22 WG21) to refer to an idiom introduced by John Barton and Lee Nackman as restricted template expansion.[1] The idiomThe idiom is characterized by an in-class friend function definition appearing in the base class template component of the curiously recurring template pattern (CRTP). // A class template to express an equality comparison interface.
template <typename T>
class EqualityComparable {
friend bool operator==(T const& a, T const& b) {
return a.equalTo(b);
}
friend bool operator!=(T const& a, T const& b) {
return !a.equalTo(b);
}
};
// Class value_type wants to have == and !=, so it derives from
// EqualityComparable with itself as argument (which is the CRTP).
class ValueType : private EqualityComparable<ValueType> {
public:
bool equalTo(ValueType const& rhs) const; // to be defined
};
When a class template like template <typename T>
bool operator==(T const& a, T const& b) {
// ...
}
would essentially be incompatible with another definition like template <typename T>
bool operator==(MyArray<T> const& a, MyArray<T> const& b) {
// ...
}
The Barton–Nackman trick, then, achieves the goal of providing a generic user-defined equality operator without having to deal with such ambiguities. The adjective restricted in the idiom name refers to the fact that the provided in-class function definition is restricted (only applies) to specializations of the given class template. The term is sometimes mistakenly used to refer to the curiously recurring template pattern (CRTP). As explained above, the Barton–Nackman trick is, instead, a distinct idiom (that relies on the CRTP). How it worksWhen the compiler encounters the expression The Barton–Nackman trick originally relied not on ADL but on a C++ feature called "friend name injection", in which an in-class declaration of a friend function made the function name visible in the immediately surrounding namespace scope (possibly the global scope). When investigating the possibility of removing friend name injection from the C++ programming language, Barton and Nackman's idiom was found to be the only reasonable use of that language rule. Eventually, the rules for argument-dependent lookup were adjusted[2] to replace friend name injection by a less drastic mechanism, described above, that maintained the validity of Barton and Nackman's technique. As a consequence of this change, the expression See alsoReferences
Further reading
|