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;
}
You need to specify the template argument explicitly, the template parameter T
can't be deduced from the context. eg
allocate<void>();
Or specify default argument for the template parameter, eg
template<typename T = void>
void allocate(){
std::cout << "default" << std::endl;
}
then you can call it as
allocate(); // T is void
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.