So, I have a macro.
// swap_specialize.hpp
#include <algorithm>
#ifndef STD_SWAP_SPECIALIZE
#define STD_SWAP_SPECIALIZE( CLASSNAME ) \
namespace std { \
template<> inline \
void swap( CLASSNAME & lhs, CLASSNAME & rhs ) \
{ lhs.swap(rhs); } }
#endif
So then I have a class
// c.hpp
#include <vector>
#include "swap_specialize.hpp"
class C
{
public:
C();
void swap(C& rhs)
{
data_.swap(rhs.data_);
}
C& operator=(C rhs)
{
rhs.swap(*this);
return *this;
}
private:
std::vector<int> data_;
}
STD_SWAP_SPECIALIZE(C)
Does the usage of a macro to specialize std::swap in this way follow coding conventions?
I would say it’s OK if it increases readability. Judge yourself. Just my two cents: Specializing
std::swapisn’t really the right way to do this. Consider this situation:This won’t find
std::swapif you haven’t doneusing std::swapor something similar. You should rather declare your own swap inC‘s namespace:Now, this will work also in the above case, because argument dependent lookup searches in the namespace of the class. Code swapping generic things where the type isn’t known should do it like this:
Regardless of the type, this will use the best matching swap, and fall-back to
std::swapif there wasn’t a better matching one in the namespaces ofa. Hard-coding the call tostd::swapwill cut too short on types that don’t specializestd::swapbut rather decide to provide their own swap in their namespace.This is superious in another way: Imagine
Cis a template. You cannot specializestd::swapin this case. But just defining your own swap, that’s perfectly fine.This is the way how the swap for
std::stringand other classes is implemented too.