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

ant*_*nef 7 c++ templates template-specialization

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

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

template <>
double test<int>(int x) { return test<double>(x); }
Run Code Online (Sandbox Code Playgroud)

max*_*x66 10

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

真正.因为你定义了test()

template <typename T>
T test(T x) { return x*x; }
Run Code Online (Sandbox Code Playgroud)

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

当你定义

template <>
double test<int>(int x) { return test<double>(x); }
Run Code Online (Sandbox Code Playgroud)

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

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

您可以通过重载解决问题

double test(int x) { return test<double>(x); }
Run Code Online (Sandbox Code Playgroud)


Rak*_*111 6

正如您所说的那样,您使用的是返回类型,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); }
Run Code Online (Sandbox Code Playgroud)

当然,有人可以随时打电话test<int>(/*...*/);.如果这是不可接受的,只需删除专业化:

template<>
int test(int) = delete;
Run Code Online (Sandbox Code Playgroud)