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

explicit specialization "..." is not a specialization of a function template

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

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

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

explicit specialization “…” is not a specialization of a function template

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

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

接收 T 类型并 return 接收 相同的 T 类型。

当你定义

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

您正在定义接收 int 值和 return 不同类型 (double) 的专业化。

所以没有匹配 T test(T)

可以通过重载来解决问题

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

如您所说,您使用的是 return 类型 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<int>(/*...*/);。如果不能接受,就删除专业化:

template<>
int test(int) = delete;