是否有可能让指针指向由奇怪的递归模板创建的基类?

时间:2014-01-13 11:01:56

标签: c++ crtp

是否有可能让指针指向由奇怪的递归模板创建的基类而不使用接口?

示例:

template<typename Derived>
class Base
{
public:
    Base();
    virtual ~Base();

    void EventA();
    void EventB();
    void EventC();

};

class DerivedA: public Base<DerivedA>
{
private:
    void EventA_imp();
    void EventB_imp();
    void EventC_imp();
};

class Manager
{
private:
    Base* base;
};

1 个答案:

答案 0 :(得分:3)

你不能,Base不是类型,Base<DerivedA>是,但是指向Base<DerivedA>的指针当然不能指定为Base<DerivedB>的指针。

你可以做的是从其他东西(比如Base)派生BaseTypeErased并指向它。然后可以将指向DerivedA类型对象的指针分配给BaseTypeErased*

class BaseTypeErased{
public:
    virtual ~BaseTypeErased(){};
};

template<typename Derived>
class Base : public BaseTypeErased
{
public:
    Base(){};
    virtual ~Base(){};

};

class DerivedA: public Base<DerivedA>
{
};

int main()
{
    BaseTypeErased* base = new DerivedA;
    delete base;
}

这是我的意思的一个例子。当然,管理方法会比较麻烦,如:

#include <iostream>

class BaseTypeErased{
public:
    void EventA(){
        EventA_imp();
    }
    virtual ~BaseTypeErased(){}
private:
    virtual void EventA_imp() = 0;
};

template<typename Derived>
class Base : public BaseTypeErased
{
public:
    Base() : derived(static_cast<Derived&>(*this)){};
    virtual ~Base(){};
private:
    void EventA_imp() override {
      derived.EventA();
    }
    Derived& derived;
};

class DerivedA: public Base<DerivedA>
{
    public:
    void EventA() {
        std::cout << "DerivedA::EventA" << std::endl;
    }
};

int main()
{
    BaseTypeErased* base = new DerivedA;
    base->EventA();
    delete base;
}