Search code examples
c++templatesstlswaptemplate-specialization

Why are there so many specializations of std::swap?


While looking at the documentation for std::swap, I see a lot of specializations.
It looks like every STL container, as well as many other std facilities have a specialized swap.
I thought with the aid of templates, we wouldn't need all of these specializations?

For example,
If I write my own pair it works correctly with the templated version:

template<class T1,class T2> 
struct my_pair{
    T1 t1;
    T2 t2;
};

int main() {
    my_pair<int,char> x{1,'a'};
    my_pair<int,char> y{2,'b'};
    std::swap(x,y);
} 

So what it is gained from specializing std::pair?

template< class T1, class T2 >
void swap( pair<T1,T2>& lhs, pair<T1,T2>& rhs );

I'm also left wondering if I should be writing my own specializations for custom classes,
or simply relying on the template version.


Solution

  • So what it is gained from specializing std::pair?

    Performance. The generic swap is usually good enough (since C++11), but rarely optimal (for std::pair, and for most other data structures).

    I'm also left wondering if I should be writing my own specializations for custom classes, or simply relying on the template version.

    I suggest relying on the template by default, but if profiling shows it to be a bottleneck, know that there is probably room for improvement. Premature optimization and all that...