Friends only class

Friends only class

Having read a few blog posts and watched a short presentation on the subject of strong typedefs, I decided to look into their use and implementation. In at least two implementations I have looked at (namely type_safe and opaque), I have found that mixin classes are used to add functionality to the new type. For instance:

class my_strong_typedef : public addable, public divisible
{};

Those mixin were implemented as empty classes that only have friend functions in them. I was wondering what was the use of such constructs. Turns out, it is an application of the Barton–Nackman trick to allow argument dependent name lookup (ADL) to find the function.

When the compiler sees the following expression:

lt + rt

it must lookup the operator+ function to use with the types of lt and rt. From my understanding, it is equivalent to an unqualified call to the operator, as in:

operator+( lt, rt )

The various name lookup rules of C++, which are not so simple, are then used to find which function to call and an important aspect in this case is that during ADL:

namespace-scoped friend functions (and function templates) that are declared in an associated class are visible through ADL even if they are not visible through ordinary lookup

which is a quote from the cppreference website. Because of that part of the standard, an operator defined as a friend in a class of which your class inherits is found. With this trick, you can, as other libraries have done, create multiple mixin classes from which your primary class inherits and ADL will find the functions. The empty classes should mostly (if not completely) be optimized away by the compiler.