Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); }
like image 388
antoinef Avatar asked Jan 28 '18 17:01

antoinef


2 Answers

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); }
like image 194
max66 Avatar answered Oct 20 '22 01:10

max66


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;
like image 30
Rakete1111 Avatar answered Oct 20 '22 00:10

Rakete1111