Я хочу иметь шаблонный класс, который смотрит что-то как то, что я имею вниз ниже. Затем я хочу функцию в нем с шаблонной специализацией в зависимости от параметра Шаблона класса. Как я делаю эту работу? Я понимаю код, который я предоставил, является неправильным на многих уровнях, но он должен только проиллюстрировать понятие.
template <typename _T, size_t num>
class Foo
{
// If num == 1, I want to call this function...
void Func<_T, 1>()
{
printf("Hi!");
}
// Otherwise, I want to call this version.
void Func<_T, num>()
{
printf("Hello world!");
}
};
struct Otherwise { };
template<size_t> struct C : Otherwise { };
// don't use _Uppercase - those names are reserved for the implementation
// (i removed the '_' char)
template <typename T, size_t num>
class Foo
{
public:
void Func() { Func(C<num>()); }
private:
// If num == 1, I want to call this function...
void Func(C<1>)
{
printf("Hi 1!");
}
// If num == 2, I want to call this function...
void Func(C<2>)
{
printf("Hi 2!");
}
// Otherwise, I want to call this version.
void Func(Otherwise)
{
printf("Hello world!");
}
//// alternative otherwise solution:
// template<size_t I>
// void Func(C<I>) { .. }
};
Частичная специализация шаблонов функций отсутствует, и для частичной специализации члена необходимо сначала частично специализировать шаблон класса.
template< typename _T, size_t num >
struct Foo {
void Func() {
printf("Hello world!");
}
};
template< typename _T >
struct Foo< _T, 1 > {
void Func() {
printf("Hi!");
}
};
Теперь, если Foo
также содержит методы, отличные от Func
, реализация которых не зависит от значения для num
, и вы не хотите дублировать их реализации в специализации Foo
, вы можете применить следующий шаблон:
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() {
...
}
};
Или, используя 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");
}
};
Это называется частичной специализацией шаблона. Это выглядит так:
template<typename _T, size_t num>
class FooBase
{
};
template <typename _T, size_t num>
class Foo : public FooBase<_T,num>
{
void Func()
{
printf("Hello world!");
}
};
template <typename _T>
class Foo<_T,1> : public FooBase<_T,num>
{
void Func()
{
printf("Hi!");
}
}