从基于模板的类继承时是否可以指定使用哪个构造函数?这似乎是一个基本的事情,但我似乎无法弄清楚如何在 C++ 中实现这一点......
在下面的代码中,我想在创建 PlayerActor(继承自 BaseActor 模板类)时对 PlayerStats 对象使用非默认构造函数。
class BaseStats {
public:
BaseStats ()
{
}
private:
};
class MonsterStats : public BaseStats {
public:
MonsterStats()
{
}
private:
};
class PlayerStats : public BaseStats {
public:
PlayerStats(
const bool is_new) :
m_is_new(is_new)
{
}
private:
const bool m_is_new;
PlayerStats(); //Don't want this being used...
};
template <class ActorStatsClass>
class BaseActor
{
public:
BaseActor()
{
}
private:
ActorStatsClass m_stats;
};
class MonsterActor: public BaseActor<MonsterStats> {
public:
MonsterActor()
{
}
private:
};
// This is where I'm not sure how to tell the template to use a non-default constructor...
// I get an error saying "PlayerStats::PlayerStats": cannot access private member declared in "PlayerStats". (Which is intended, but I don't want it to try and use the default constructor...)
class PlayerActor : public BaseActor<PlayerStats> {
public:
PlayerActor(const bool is_new)
{
}
private:
PlayerActor(); // Don't use this...
};
Run Code Online (Sandbox Code Playgroud)
template <class ActorStatsClass>
class BaseActor
{
public:
BaseActor()
{
}
private:
ActorStatsClass m_stats;
};
Run Code Online (Sandbox Code Playgroud)
如果此类BaseActor将具有任意成员,则它需要构造这些任意成员的方法。所以它需要一个通用的构造函数。
template <class ActorStatsClass>
class BaseActor
{
public:
template<class...Us>
BaseActor(Us&&...vs)
: m_stats(std::forward<Us>(vs)...)
{ }
private:
ActorStatsClass m_stats;
};
Run Code Online (Sandbox Code Playgroud)
这使用转发,无论参数传递给BaseActor,它只是将它们直接传递到构造m_stats成员。
这允许:
class PlayerActor : public BaseActor<PlayerStats> {
public:
PlayerActor(const bool is_new)
: BaseActor<PlayerStats>(is_new)
{ }
PlayerActor() = delete; // Note: this is better than making it private
};
Run Code Online (Sandbox Code Playgroud)