The usual definition for a specialization of a template function is something like this:
class Foo {
[...]
};
namespace std {
template<>
void swap(Foo& left, Foo& right) {
[...]
}
} // namespace std
But how do you properly define the specialization when the type it’s specialized on is itself a template? Here’s what I’ve got:
template <size_t Bits>
class fixed {
[...]
};
namespace std {
template<size_t Bits>
void swap(fixed<Bits>& left, fixed<Bits>& right) {
[...]
}
} // namespace std
Is this the right way to declare swap? It’s supposed to be a specialization of the template function std::swap, but I can’t tell whether the compiler is seeing it as such, or whether it thinks that it’s an overload of it or something.
Your solution isn’t a template specialization, but an overload of a function in the std namespace, which is “undefined behavior” per the c++ standard.
This question is exactly your question.
Scott Meyers discusses this in Effective C++, and there is a followup thread on usenet’s comp.lang.c++.
If you’re seeing compilation errors when trying to define this in namespace std, it’s likely due to your unfortunate choice of class names 🙂 When within
namespace std“fixed” is being seen asstd::fixed, the floating point precision operator.