【问题标题】:explicit specialization "..." is not a specialization of a function template显式特化“...”不是函数模板的特化
【发布时间】:2018-01-28 17:08:05
【问题描述】:

我正在尝试专门化一个函数模板,但我遇到了一个错误(标题),我不知道如何解决它。我猜这是由于我在模板专业化中使用的混合类型。这个想法只是在专业化中使用 int 作为 double 。非常感谢。

template <typename T>
T test(T x) { return x*x; }

template <>
double test<int>(int x) { return test<double>(x); }

【问题讨论】:

  • double test(int) 不匹配 T test(T),因此出现错误。

标签: c++ templates template-specialization


【解决方案1】:

显式特化“...”不是函数模板的特化

没错。 因为你定义了test()

template <typename T>
T test(T x) { return x*x; }

接收T 类型并返回相同 T 类型。

当你定义时

template <>
double test<int>(int x) { return test<double>(x); }

您正在定义一个接收 int 值并返回不同类型 (double) 的特化。

所以没有匹配到T test(T)

可以通过重载来解决问题

double test(int x) { return test<double>(x); }

【讨论】:

    【解决方案2】:

    正如你所说的,你使用的是返回类型T = double,但参数T = int是无效的。

    你可以做的是提供一个非模板化的重载:

    template<typename T>
    T test(T x) { return x*x; }
    
    // regular overload, gets chosen when you call test(10)
    double test(int x) { return test<double>(x); }
    

    当然,有人可以随时拨打test&lt;int&gt;(/*...*/);。如果这不可接受,只需删除专业化:

    template<>
    int test(int) = delete;
    

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多