Thursday, June 05, 2008

C++ : std::swap and template specialization

say you want to use the swap method provided in std namespace for your own class . Then instead of using the std::swap option blindly , that would involve making use that your class has at least a copy constructor and that the assignment operator is overridden.

It makes more sense to use template specialization for std::swap

class MyClass {
public:
void Swap(MyClass &) ;
};

namespace std {
template<> swap(MyClass& a, MyClass& b){
a.Swap(b);
}
}

so that way we just tune the default swap to use our class specific Swap and things become fast and simple for us .

No comments: