I want to have a template class that looks something like what I have down below. Then, I want a function in it with a template specialization depending on a CLASS template para
There are no partial specialisations of function templates, and to partially specialise a member you need to first partially specialise the class template.
template< typename _T, size_t num >
struct Foo {
void Func() {
printf("Hello world!");
}
};
template< typename _T >
struct Foo< _T, 1 > {
void Func() {
printf("Hi!");
}
};
Now, if Foo also contains methods other than Func whose implementation is independent of the value for num, and you don't want to duplicate their implementation in the specialization of Foo, you can apply the following pattern:
template< typename _T, size_t num >
struct FooFuncBase {
void Func() {
printf("Hello world!");
}
};
template< typename _T >
struct FooFuncBase< _T, 1 > {
void Func() {
printf("Hi!");
}
};
template< typename _T, size_t num >
struct Foo : public FooFuncBase< _T, num > {
void OtherFuncWhoseImplementationDoesNotDependOnNum() {
...
}
};
Or, using CRTP:
template< typename _Derived, typename _T, size_t num >
struct FooFuncBase {
void Func() {
static_cast< _Derived* >(this)->OtherFuncWhoseImplementationDoesNotDependOnNum();
printf("Hello world!");
}
};
template< typename _Derived, typename _T >
struct FooFuncBase< _Derived, _T, 1 > {
void Func() {
static_cast< _Derived* >(this)->OtherFuncWhoseImplementationDoesNotDependOnNum();
printf("Hi!");
}
};
template< typename _T, size_t num >
struct Foo : public FooFuncBase< Foo< _T, num >, _T, num > {
void OtherFuncWhoseImplementationDoesNotDependOnNum() {
printf("Other");
}
};