C++:派生模板 class 和基础 class 之间的向下转型和向上转型?
C++: downcasting and upcasting between derived template class and base class?
我无法将指向模板派生 class 的指针转换为基本 class 指针以存储在地图中(显然稍后会检索它。)。我有:
#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;
}
为什么会这样,有没有办法解决这个问题,这样我就可以用枚举值模板化 class,以便通过 getClass<Enum>
函数进行外部调用,希望在例如?
问题很简单:你重新定义了角色
template<> class Role<RoleEnum::Player> {}
不扩展 RoleBase.
删除它或将其更改为:
template<> class Role<RoleEnum::Player> : public RoleBase {}
我无法将指向模板派生 class 的指针转换为基本 class 指针以存储在地图中(显然稍后会检索它。)。我有:
#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;
}
为什么会这样,有没有办法解决这个问题,这样我就可以用枚举值模板化 class,以便通过 getClass<Enum>
函数进行外部调用,希望在例如?
问题很简单:你重新定义了角色
template<> class Role<RoleEnum::Player> {}
不扩展 RoleBase.
删除它或将其更改为:
template<> class Role<RoleEnum::Player> : public RoleBase {}