0

I am having this template matching error. I know partial specialization is not allowed in for function template, but I think it should work with full specialization. What change do I need to make to fix this issue ? Thanks.

#include <iostream> template<typename T> void allocate(){ std::cout << "default" << std::endl; } template<> void allocate<int>() { std::cout << "int" << std::endl; } template<> void allocate<double>() { std::cout << "double" << std::endl; } int main() { allocate(); // Compiler error, I expect this should match the first template function. allocate<int>(); allocate<double>(); return 0; } 

2 Answers 2

1

You need to specify the template argument explicitly, the template parameter T can't be deduced from the context. e.g.

allocate<void>(); 

Or specify default argument for the template parameter, e.g.

template<typename T = void> void allocate(){ std::cout << "default" << std::endl; } 

then you can call it as

allocate(); // T is void 
Sign up to request clarification or add additional context in comments.

Comments

0

The primary template needs the template parameter to be specified explicitly, so you can do:

allocate<struct T>(); // ok 

and since T is a new type named only for the purpose of this call, there is guaranteed to not be a specialization for this type, and the primary template will be called.


You could also give a default type for the template parameter in the primary:

template<typename T = struct Default> void allocate(){ std::cout << "default" << std::endl; } 

and again, no specialization can exist for Default since this type only exists in the scope of the primary template.

Now you can call the primary template without template parameters:

allocate(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.