To have a sort of duck typing, I do
template<bool b>
struct A{
static template<typename V> f1(V*, [other params]);
static template<typename V> f2(V*, [other params]);
};
template<> template<typename T>
void A<false>::f1(V*, [other params]){}
template<> template<typename T>
void A<true>::f1(V*, [other params]){
...some code...
}
template<int flags>
struct V{
void f(){
A<flags&Some compile time conditions>::f1 (this,[params]);
A<flags&Some compile time conditions>::f2 (this,[params]);
}
};
Do you think there is a more elegant solution, which is not Template class, function specialization
(I do not want to add an extra param to the functions)
I would like to do something like
template<int X> struct C{
void f(){std::cout<<"C::f"<<std::endl;};
};
template<> struct C<0>{
};
template<int X> struct D{
C<X> c;
template<bool b>
void f();
void g(){
f<X!=0>();
}
};
template<>
template<int X>
void D<X>::f<true>{
c.f();
};
template<int X>
template<>
void D<X>::f<false>{};
int main(){
D<3> ch;
ch.g();
D<0> cn;
cn.g();
}
but this is not valid code, and I get error: template-id ‘f’ used as a declarator.
Is there a way to specialize a template function by the value of its non-type template parameter?
That is illegal (all attempts are). When you specialize a member function template, it’s enclosing class has to be specialized as well.
However, you can overcome that easily by wrapping your function inside a templated struct that would take its template arguments. Something like
and call it with
DXF<X, (X!=0)>::f().However, it seems that you just want to specialize for
X==0. In that case, you can just specialize:Note that
fin that case is not a member template.Another option you can go for is overloading. You could wrap your
intin a parameter list of some template, like this:Note that true_type and false_type are just
typedefs ofstd::integral_constant<bool, true>andfalse, resp.