C ++:派生模板类和基类之间的向下转换和向上转换?

时间:2016-11-05 14:10:25

标签: templates casting static-cast static-polymorphism

我无法将指向模板化派生类的指针转换为基类指针,以便存储在地图中(显然稍后会检索它)。我有:

#include <map>
//Role.h
class RoleBase{};
enum class RoleEnum : int;

template<RoleEnum role>
class Role : public RoleBase{};

//Relationship.h
class Relationship{
public:
    template<RoleEnum role>
    Role<role>* getRole(){
    auto it=RoleMap.find(role);
    if ( it == RoleMap.end() ) {
       return nullptr;
    } else {
            RoleBase* roleBase= it->second;
            return static_cast<Role<role>* >(roleBase);
        }
    }
    std::map<RoleEnum,RoleBase*> RoleMap;
};

//squash.h
enum class RoleEnum : int
{
    Player,
    Referee
};

template<> class Role<RoleEnum::Player>{};
template<> class Role<RoleEnum::Referee>{};

class SquashGame: public Relationship{
public:
    SquashGame(){
        RoleBase* playerRole=new Role<RoleEnum::Player>; //problematic
        RoleMap.emplace(RoleEnum::Player,playerRole);
    }
};

int main() {
    SquashGame squashGame;
    squashGame.getRole<RoleEnum::Player>();
    return 0;
}

为什么会这样,有没有办法解决这个问题,所以我可以使用枚举值来模拟一个类,以便通过getClass<Enum>函数进行外部调用,这在示例中有希望清楚?

1 个答案:

答案 0 :(得分:1)

问题很简单:重新定义角色

template<> class Role<RoleEnum::Player> {}

不会扩展 RoleBase

删除它或将其更改为:

template<> class Role<RoleEnum::Player> : public RoleBase {}