gpt4 book ai didi

c++ - 避免在构造函数中使用虚方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:52:53 24 4
gpt4 key购买 nike

假设我有以下类层次结构:

class Base
{
virtual int GetClassID(){ return 0;};
public:
Base() { SomeSingleton.RegisterThisObject(this->GetClassID());
}

class Derived
{
virtual int GetClassID(){ return 1;};
public:
Derived():Base(){};
}

好吧,这一切都是从我的真实案例中简化而来的,但这就是它的一般要点。

我想避免在每个派生类的构造函数中调用 RegisterThisObject,因此我试图将调用移至基类的构造函数。

有没有什么模式可以让我在不使用构造函数中的虚拟方法的情况下完成这个?

最佳答案

您可能会使用 Curiously Recurring Template Pattern

template <class T>
class Base
{
protected: // note change
Base() { SomeSingleton.RegisterThisObject(T::GetClassID());
}

class Derived : Base<Derived>
{
static int GetClassID(){ return 1;};
public:
Derived(): Base<Derived>(){};
}

此外,当您有多个 派生类时(比如 DerivedDerived : Derived),这将需要额外的工作。我建议您简单地避免这种情况,但在其他情况下,您可能希望将注册移至策略类中(使行为可聚合,而不是类标识的一部分)

特质

扩展我的提示(使行为可聚合),您会看到类似这样的内容:

namespace detail
{
template <class T> struct registerable_traits { };
template<> struct registerable_traits<Derived>
{
enum _id { type_id = 1 };
};
}

template <class T>
class Base
{
protected: // note change
Base() { SomeSingleton::RegisterThisObject(detail::registerable_traits<T>::type_id); }
};

class Derived : Base<Derived>
{
public:
Derived(): Base<Derived>(){};
};

参见 Codepad.org

关于c++ - 避免在构造函数中使用虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6582239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com