我有以下基类:
template <template<class Type> class T2>
class FundamentalClass {
typename T2<double> *_compose1;
typename T2<int> *_compose2;
protected:
FundamentalClass(); // Insert constructors here.
template<class Strategy>
T2<typename Strategy::Type> *Construct(void);
public:
template <class Strategy>
T2<typename Strategy::Type> *GetComposedObject(void);
};
带
template< template<class Type> class T2>
template<>
T2<double> *FundamentalClass<T2<double> >::GetComposedObject<DoubleStrategy>(void) {
if( NULL == _compose1) {
_compose1 = Construct<DoubleStrategy>(void);
}
return _compose1;
}
每个组合对象的其他特化。
但是,我需要构造由派生类实现。没有模板,Construct就是虚拟的。我怎样才能实现这一目标?
答案 0 :(得分:4)
您可以通过Curiously Recurring Template Pattern (CRTP):
使用编译时多态性来完成此操作template <template<class Type> class T2, class Derived>
class FundamentalClass {
...
template<class Strategy>
T2<typename Strategy::Type> *Construct() {
return static_cast<Derived *>(this)->DoConstruct<Strategy>();
}
在Derived
中,写一下:
template <template<class Type> class T2>
class Derived: public FundamentalClass<T2, Derived<T2> >
{
public:
template<class Strategy>
T2<typename Strategy::Type> *DoConstruct() {
...
}