【问题标题】:Syntax for specializing function templates专门化函数模板的语法
【发布时间】:2010-04-30 20:22:37
【问题描述】:

以下方法有区别吗?

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

当我尝试专门交换我自己的字符串类型时,我偶然发现了这一点,并注意到 swap&lt;::string&gt; 不起作用,但原因完全不同:)

【问题讨论】:

  • ::string 是什么类型的?
  • 全局命名空间中我自己的玩具字符串类型。

标签: c++ templates swap


【解决方案1】:

是的,有。但不是在那个特定的例子中。如果不推导出参数,可以有所作为

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

如果没有&lt;type&gt;,您将无法对其进行专门化,因为它无法从参数列表中推断出T 是什么。

struct MyType { typedef int type; };

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

当然,在您的情况下,有向图 &lt;:[ 的含义相同导致您的问题。放置&lt;::string&gt; 之类的空格以避免出现问题。

【讨论】:

  • +1 感谢您的解释!这个有向图的东西太有趣了:)
  • 您知道是什么导致该语法在标准中被允许吗?暂时没看到。
  • @gf 你的意思是f&lt;..&gt; 语法?它是一个template-id,它是一个id-expression,它是一个declarator-id。
  • 我指的是template&lt;&gt; R f(T)而不是template&lt;&gt; R f&lt;T&gt;(T)的特化语法。
  • @gf,见 14.8.1/2 和 14.7.3/11
【解决方案2】:

此外,你不需要专门研究这种情况,只需超载并快乐。

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

【讨论】:

  • 如果你喜欢未定义的行为,那么是的 :) 你不能在 std 命名空间中重载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多