函数模板获取:转换需要reinterpret_cast,C样式转换或函数式转换错误

时间:2016-11-30 09:59:25

标签: c++ templates compiler-errors

我有一个如下所示的功能模板:

HelloWorld.h

template<typename T>
    bool NodeTraverse(T* &pGameObj);

HelloWorld.cpp

template<typename T>
bool HelloWorld::NodeTraverse(T* &pGameObj)
{
}

我传递给2种类型的功能 有时A_object和Somtimes B_obejct都在实现相同的接口IGame

class IGame
{
public:
    virtual ObjType getType() = 0;
    virtual void setType(ObjType ot) = 0;

protected:
    ObjType objtype;


};

class A_object:public IGame { 上市:     A_object();     ObjType getType(){return objtype; }     void setType(ObjType ot){objtype = ot; } }

class A_object : public IGame
{
public:
    A_object();
    virtual ~A_object();
    ObjType getType() { return objtype; }
    void setType(ObjType ot) { objtype = ot; }
}

class B_object : public IGame
{
public:
    B_object();
    virtual ~B_object();
    ObjType getType() { return objtype; }
    void setType(ObjType ot) { objtype = ot; }
}

现在我这样称呼NodeTraverse:

A_object * pA_object = new A_object() ;
pA_object ->setType(A_OBJECT);

NodeTraverse(pA_object);
到目前为止一切都很好。 但是,当我编译应用程序即时令人担忧

2>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
2>          d:\\classes\helloworldscene.cpp(114) : see reference to function template instantiation 'bool HelloWorld::NodeTraverse<A_object >(T *&)' being compiled
2>          with
2>          [
2>              T=A_object 
2>          ] 

但问题是我还得到编译错误,当我这样做时,我怀疑这是错误的:

if (gameObjParent->getType() == LAYER_OBJECT)
{
    pGameObj = ((A_object *)gameObjParent);
}
else if (gameObjParent->getType() == SPRITE_OBJECT)
{
    pGameObj = ((B_object *)gameObjParent);  // HERE IS THE COMPILATION ERROR 
}

有些人认为gameObjParent是A_object * 这是错误: 它高于模板工作

2>d:\classes\helloworldscene.cpp(200): error C2440: '=' : cannot convert from 'B_object *' to 'A_object *'
2>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
2>          d:\\classes\helloworldscene.cpp(114) : see reference to function template instantiation 'bool HelloWorld::NodeTraverse<A_object >(T *&)' being compiled
2>          with
2>          [
2>              T=A_object 
2>          ]

有线部分是编译错误。为什么?

0 个答案:

没有答案