One option that you have to make your overload βworseβ than alternatives. Then, only if they do not exist yet, your version will be selected:
#if 0 #include <algorithm> using std::swap; #endif template <typename T> struct ForceLessSpecialized { typedef T TYPE; }; template <typename T> void swap (T &, typename ForceLessSpecialized<T>::TYPE &) { } void bar () { int i; swap (i, i); }
What's happening:
If there are two specialized function templates, the compiler performs "Partial ordering of function templates" ('03 14.5.5.2). This checks if the template parameters of the function of one template can be used to specialize another.
For each template, we will use dummy parameters T1 and T2 , and we create lists of dummy arguments using the following types:
Specializing in our swap using dummy arguments from std::swap , we get:
Deduction from First parameter: T == T1 Deduction from Second parameter: Non Deduced Context
The inferred T is equal to T1 , and the residue succeeded.
Specializing std::swap using dummy arguments for our swap, we get:
Deduction from First parameter: T == T2 Deduction from Second parameter: T == ForceLessSpecialized<T2>::TYPE
The deduced types for T do not match, and therefore this is considered a deduction failure.
Therefore, the synthesized arguments to std::swap can be used to specialize our template, but the synthesized arguments to our template cannot be used to specialize std::swap . std::swap considered as more specialized and therefore partial order wins.
Richard Corden
source share