I'm trying to specialize a function template but I'm getting an error (title) and I don't know how to solve it. I'd guess it is due to the mixed types I use in the template specialization. The idea is just to use int as double in the specialization. Many thanks.
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
True.
Because you defined test()
template <typename T>
T test(T x) { return x*x; }
receiving a T
type and returning the same T
type.
When you define
template <>
double test<int>(int x) { return test<double>(x); }
you're defining a specialization that receive a int
value and return a different type (double
).
So there is no match with T test(T)
.
You can solve the problem through overloading
double test(int x) { return test<double>(x); }
As you correctly said, you are using for the return type T = double
but for the parameter T = int
, which isn't valid.
What you can do instead is provide a non-templated overload:
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); }
Of course, someone can always call test<int>(/*...*/);
. If that is not acceptable, just delete the specialization:
template<>
int test(int) = delete;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With