Example:
std::swap . The basic swap template swaps two values
a and
b by creating a
temp copy of
a , assigning
a = b , and assigning
b = temp . How can you extend it for your own types? For example, let's say you have your own type
Widget in your own namespace
namespace N { class Widget {
/* … */ }; }
Suppose that you have a more efficient way to swap two
Widget objects. To enable it for use with the standard library, should you provide an overload of
swap (in the same namespace as
Widget ; see Item 57) or specialize
std::swap directly? The standard is unclear, and existing practice varies considerably (see Item 65). Today, in practice, on some implementations a correct answer is to provide an overload in the same namespace as
Widget . For the above nontemplate
Widget :
namespace N { void swap( Widget&, Widget& ); }
But note that if
Widget is instead a template,
namespace N { template<typename T> class Widget {
/*…*/ }; }
then specializing
std::swap isn't even possible, because there's no such thing as a partial specialization of a function template. The best you can do is add the overload:
namespace ??? { template<typename T> void swap( Widget<T>&, Widget<T>& ); }
but this is problematic because if you put it in the namespace of
Widget , then many implementations won't find it, but the standard forbids you from putting it in
std . Catch-22. This problem would not exist if the standard either specified that overloads in the namespace of the type will be found, or allowed you to add overloads to namespace
std , or (getting back to the point of this Item) specified
swap to be implemented in terms of a class template that you