我在从同一模板类的不同实例进行多重继承时遇到问题。具体来说,我正在尝试这样做:
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
最佳答案
It seems to imply that there is an instantiation
createBase< SomethingElse >
inBase< 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/