有功能 模板没有偏特,以及部分专业需要先 部分专业类模板的成员。
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");
}
};
我喜欢这个解决方案。我甚至学到了关于C++命名约定的知识!然而,如果我有,例如,任何数量的专业化的数量的num和随后的情况下,他们都不工作,我该如何做到这一点? – 2010-02-28 04:24:13
@wowus,已更新回答 – 2010-02-28 04:32:29
谢谢,接受。 – 2010-02-28 04:40:59