繁体   English   中英

C ++设计问题:我可以查询基类以找到满足条件的派生类的数量

[英]c++ design question: Can i query the base classes to find the number of derived classes satisfying a condition

我有一段这样的代码

class Base
{
public:
Base(bool _active)
{
 active = _active;
}
void Configure();
void Set Active(bool _active);
private: 
bool active;
};
class Derived1 : public Base
{
public:
Derived1(bool active):Base(active){}

};

similarly Derived 2 and Derived 3

现在,如果我调用derived1Object.Configure,则需要检查有多少个derived1Obj,derived2Obj,derived3Obj是活动的。 我是否应该像函数说的那样将其添加到“ Base”类中,例如GetNumberOfActive()?

如果实现是这样的:

class Imp
{
public:
 void Configure()
 {
  //Code instantiating a particular Derived1/2/3 Object 
  int GetNumberOfActiveDerivedObj();
  baseRef.Configure(int numberOfActiveDerivedClasses);
 }
prive:
Derived1 dObj1(true);
Derived2 dObj2(false);
Derived3 dObj3(true);
};

我应该计算Imp类中的numberOfActive派生对象吗?

谢谢

一种简单的可能性:

NumberOfActiveBase应该是static的。 每次创建对象且active为true时,它应该增加。

您可以将CRTP与静态计数器变量结合使用: Wikipedia链接

编辑:一些代码

#include <iostream>

template <typename T> struct counter {
    counter() { ++objects_alive; }
    virtual ~counter() { --objects_alive; }
    static int objects_alive;
};
template <typename T> int counter<T>::objects_alive( 0 );


class Base {
public:
    void Configure();
    //more stuff
};

class Derived1 : public Base, counter<Derived1> {
public:
    void Configure() {
        std::cout << "num Derived1 objects: "<< counter<Derived1>::objects_alive << std::endl;
    }
};

class Derived2 : public Base, counter<Derived2> {
public:
    void Configure() {
        std::cout << "num Derived2 objects: " << counter<Derived2>::objects_alive << std::endl;
    }
};

int main (int argc, char* argv[]) {

    Derived1 d10;
    d10.Configure();
    {
        Derived1 d11;
        d11.Configure();
        Derived2 d20;
        d20.Configure();

    }
    Derived1 d12;
    d12.Configure();
    Derived2 d21;
    d21.Configure();


    return 0;
}

输出:

$ g++-4 -pedantic crtp1.cpp -o crtp1 && ./crtp1
num Derived1 objects: 1
num Derived1 objects: 2
num Derived2 objects: 1
num Derived1 objects: 2
num Derived2 objects: 1

在Configure()方法中,您可以访问Derived *对象的工厂并获取活动对象的数量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM