Syntax for specialized function templates

Is there any difference between the following approaches?

// approach 1 namespace std { template<> void swap<Foo>(Foo& x, Foo& y) // note the <Foo> { x.swap(y); } } // approach 2 namespace std { template<> void swap(Foo& x, Foo& y) { x.swap(y); } } 

I attacked this when I tried to specialize swap for my own string type and noticed that swap<::string> did not work, but for a completely different reason :)

+6
c ++ swap templates
source share
2 answers

Yes there is. But not in this specific example. If the parameter is not displayed, it may have a value

 template<typename T> void f(typename T::type t); 

You cannot specialize in this without <type> , because it cannot deduce that T from the parameter list.

 struct MyType { typedef int type; }; // needs <MyType> template<> void f<MyType>(int t) { } 

Of course, in your case it is a digraph <: which means the same as [ , causing your problem. Put a space like < ::string> to avoid the problem.

+8
source share

In addition, you do not need to specialize in this case, just overload and be happy.

 namespace std { void swap(Foo& x, Foo& y) { x.swap(y); } } 
0
source share

All Articles