Consider the following template
template <typename T, int v> void func(const T&x);
and I want to specialize it for some class A
. Here is my try (by referring to this):
template <int v> void func<A, v>(const A&x);
However, that's illegal. My question is why this is illegal (which rule it breaks) and if that is against the grammar, is there other ways for us to specialize it for A
?
CodePudding user response:
You cannot partially specialize a function template but you can overload it as shown below.
#include <iostream>
class A
{
};
template <typename T, int v> void func(const T&x) //primary template
{
std::cout<<"primary template"<<std::endl;
}
//this is an overload and not a specialization. Also partial specialization cannot be done for function templates
template <int v> void func(const A&x)
{
std::cout<<"overload not specialization"<<std::endl;
}
int main()
{
func<int, 5>(84); //uses primary template
func<5>(A()); //uses the overloaded version
return 0;
}
CodePudding user response:
Function templates cannot be partially specialized, hence the error:
<source>:8:23: error: non-class, non-variable partial specialization 'func<A, v>' is not allowed
8 | template <int v> void func<A, v>(const A&x);
| ^~~~~~~~~~
You can for example partially specialize a type with operator()
:
template <typename T, int v>
struct func{
void operator()(const T&x);
};
struct A {};
template <int v>
struct func<A, v>{
void operator()(const A&x);
};
CodePudding user response:
you can do it with
template <typename T, int v> void func(const T&x);
template <int v> void func(const A&x);
as for why, I think it mainly because it provide no additional value
template <typename T> void func(const T&x);
template <typename T> void func(const T*x);
void func(const A&);
is already a valid function "specialization". not really specialization in the sense of standard wording