fredoverflow
fredoverflow

Reputation: 263148

Syntax for specializing function templates

Is there a 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 stumpled upon this when I tried to specialize swap for my own string type and noticed that swap<::string> doesn't work, but for a completely different reason :)

Upvotes: 6

Views: 157

Answers (2)

dash-tom-bang
dash-tom-bang

Reputation: 17853

Additionally, you don't need to specialize in this case, just overload and be happy.

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

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507055

Yes, there is. But not in that particular example. If the parameter is not deduced, it can make a difference

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

You cannot specialize that without <type> because it cannot deduce what T is from the parameter list.

struct MyType { typedef int type; };

// needs <MyType>
template<> void f<MyType>(int t) { }

Of course in your case, it's the digraph <: that's meaning the same as [ causing your problem. Put a space like < ::string> to avoid the problem.

Upvotes: 8

Related Questions