c++ - 从模板类多重继承

标签 c++ inheritance templates multiple-inheritance

我在从同一模板类的不同实例进行多重继承时遇到问题。具体来说,我正在尝试这样做:

template <class T>
class Base
{

public:

    Base() : obj(NULL)
    {
    }

    virtual ~Base()
    {
        if( obj != NULL ) delete obj;
    }

    template <class T>
    T* createBase()
    {
        obj = new T();

        return obj;
    }

protected:

    T* obj;

};

class Something
{
    // ...
};

class SomethingElse
{
    // ...
};

class Derived : public Base<Something>, public Base<SomethingElse>
{

};

int main()
{
    Derived* d = new Derived();
    Something* smth1 = d->createBase<Something>();
    SomethingElse* smth2 = d->createBase<SomethingElse>();

    delete d;

    return 0;
}

当我尝试编译上面的代码时,出现以下错误:

1>[...](41) : error C2440: '=' : cannot convert from 'SomethingElse *' to 'Something *'
1>        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>        [...](71) : see reference to function template instantiation 'T *Base<Something>::createBase<SomethingElse>(void)' being compiled
1>        with
1>        [
1>            T=SomethingElse
1>        ]
1>[...](43) : error C2440: 'return' : cannot convert from 'Something *' to 'SomethingElse *'
1>        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

由于成员 obj 是从 Base< Something > 和 Base< SomethingElse > 继承的,所以这个问题似乎是不明确的,我可以通过消除对 createBase 的调用来解决这个问题:

Something* smth1 = d->Base<Something>::createBase<Something>();
SomethingElse* smth2 = d->Base<SomethingElse>::createBase<SomethingElse>();

但是,从句法上讲,这个解决方案非常不切实际,我更喜欢更优雅的方法。此外,我对第一条错误消息感到困惑。这似乎意味着在 Base 中有一个实例化 createBase,但这怎么可能呢?非常感谢有关此问题的任何信息或建议。

最佳答案

It seems to imply that there is an instantiation createBase< SomethingElse > in Base< Something >, but how is that even possible?

肯定有,因为你的 createBase<T>()是成员模板函数(该函数中的T与周围类中的T无关)。

我会做类似的事情:

// in Derived, or you could make some class (eg. MultiBase) for it

template <class T>
T* createBase()
{
  return Base<T>::createBase();
}

关于c++ - 从模板类多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2878252/

相关文章:

c++ - 在 Qt (C++) 中使用第三方库 (libconfig)

c++ - 如何为元素( vector 和整数)也是 unique_ptr 的对创建 unique_ptr?

templates - Handlebars.js if block 助手 ==

ruby - 将类添加到菜单中的事件列表

c++ - 对指针 vector 进行排序工作一次然后崩溃 "unable to read memory"

c++使用枚举创建类会产生错误

c++ - 给定抽象基类 X,如何创建另一个模板类 D<T>,其中 T 是从 X 派生的类的类型?

java - Java中扩展类的构造函数

python - Python 3 中从外部父类的嵌套类继承的嵌套类

c++ - 可以写类似 "f<N> can compile only when N>0"的东西吗?