我在使用不同实例化模板类的多继承时遇到了问题。具体来说,我正在尝试做以下操作:
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 的实例化,但这怎么可能呢?非常感谢您对此问题提供任何信息或建议。
typedef
。 - Xavier Ho