开发者

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) 开发者_C百科  // 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 :)


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.


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜