使用模板的"虚拟"方法
"virtual" method with templates
我有以下基类:
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将是虚拟的。我该如何实现这个目标?
您可以通过Curioly 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() {
...
}
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 使用模板而不是虚拟方法的管道模式
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 为什么调用没有正文的纯虚拟方法不会导致链接器错误?
- 出于什么目的,非虚拟方法将与C++一起使用?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 如何重写继承的嵌套类中存在的虚拟方法
- 私有虚拟方法有什么用?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 确保模拟的 GTest 方法覆盖虚拟方法
- CPP 继承虚拟方法解析顺序
- 我是否应该在包含虚拟方法的类上使用'memcpy'?如果没有,如何替换它?
- 用c++中的纯虚拟方法抽象模板类
- 解决虚拟方法的歧义继承的两种方法
- 没有针对完全专用模板类的外联虚拟方法定义