[RFC] how to test for swap specializations?

Martin Sebor sebor@roguewave.com
Tue Mar 2 00:49:00 GMT 2004


Benjamin Kosnik wrote:

> 
> Anybody have any ideas on how to test for this? (It's what is left of
> libstdc++/13658)
> 
> #include <vector>
> 
> int main()
> {
>   // Should use vector specialization for swap, and does not.

If you mean the template overload of std::swap() for std::vector,
it should be possible for the test to explicitly specialize the
template on some user-defined type T and call std::swap() on that
specialization of vector. Like this:

   struct T { int i; };

   int swap_calls = 0;

   template<>
   void std::swap<T, allocator<T> > (vector<T>&, vector<T>&) {
     ++swap_calls;
   }

   std::vector<T> A;
   std::vector<T> B;
   std::swap (A, B);
   assert (1 == swap_calls);

This exercises the library, though, not the compiler's ability
to resolve the call to the specialization the same way it would
to the primary template if the former did not exist. I.e., the
test assumes the compiler behaves in a sane way. It seems that
the bug involved the compiler, and not so much the library, so
a more reliable test case, one not involving the library, might
go in the compiler's test suite.

Alternatively, since the vector overload of std::swap() just
calls vector::swap(), you could explicitly specialize the swap()
member function on the same user-defined T and do the check
there:

   template<>
   void std::vector<T>::swap (vector<T>&) {
     ++swap_calls;
   }

This exercises both the library (that std::swap() calls the
vector member swap()) but also the compiler (i.e., that it
doesn't call the generic std::swap() from <algorithm>).

Martin



More information about the Libstdc++ mailing list