避免构造函数中的虚方法 [英] Avoiding virtual methods in constructor

查看:125
本文介绍了避免构造函数中的虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下类层次结构:

Say I have the following class hierarchy:

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

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

好吧,这是从我的真实情况简化的,但这是一般的要点它。

Well, it's all simplified from my real case, but that's the general gist of it.

我想避免在每个派生类的构造函数中调用RegisterThisObject,所以我试图将调用移动到基类的构造函数。

I want to avoid having to call RegisterThisObject in the constructor of each derived class, so I'm trying to move the call to the constructor of the base class.

有没有任何模式,我可以使用来实现这一点,而不使用虚拟方法在构造函数?

Is there any pattern that I can use to acomplish this without using the virtual method in the constructor?

推荐答案

您可以使用Curiously Recurring Template Pattern

You might use the 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>(){};
}

此外,当您有多个 / em>派生类(例如 DerivedDerived:Derived )。我建议你只是避免,但在其他情况下,你可能想移动注册到策略类(使行为可聚合而不是类身份的一部分)

Also, it will require extra work when you have multiple generations of derived classes (say DerivedDerived : Derived). I'd suggest you simply avoid that but in other cases you might want to move the registration into a policy class instead (make the behaviour aggregatable as opposed to a part of the class identity)

扩展我的提示(使行为可聚集像这样:

Expanding on my hint (make the behaviour aggregatable), you'd see something like this:

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

这篇关于避免构造函数中的虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆