views:

126

answers:

2

I just start learning metaprogramming, I wonder the implementation of swap. Can anyone help me and explain the idea of traits in metaprogramming? thanks.

+2  A: 

From http://www.cplusplus.com/reference/algorithm/swap/:

The behavior of this function template is equivalent to:

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}
Oli Charlesworth
+7  A: 

std::swap from <algorithm> is implemented as a template, so that it can exchange the values of two variables of any given type. Its prototype looks like this:

template <typename T> void swap(T& a, T& b);

The typical implementation is to save one value in a temporary, copy the second value to the first variable, and then to put the temporary value into the second variable. In C++, this involves a copy constructor and assignment operators.

For large objects, all of that construction and copying can be expensive. So many objects, including most (all?) of the STL containers have an overloaded implementation that works by exchanging a few pointer values. Exchanging pointers is very fast, and it avoids any potential failures (like memory allocation during the copy constructor). The overloaded std::swap forwards to a member function (often also called swap). The member function has access to the internals, so it can use a more efficient approach. The overload might look something like this (simplified):

template <typename T> void swap<vector<T> >(vector<T>& a, vector<T>& b) {
  a.swap(b);
}

If you want to see the real code, you can browse the std header files for your compiler and OS.

Adrian McCarthy
Quibble: that's actually an overload of `std::swap`, rather than a (template) specialization, although the standard does refer to them as "specialized algorithms". It's exactly the signature of the one for `std::vector`, except that `vector` has two template parameters, `<T,Allocator>`, rather than just one.
Steve Jessop
@Steve Jessop: Thanks for the clarification. I've edited the answer based on your feedback.
Adrian McCarthy