c++ design question: Can i query the base classes to find the number of derived classes satisfying a condition
I have a piece of code like this
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
Now if i call derived1Object.Configure, i need to check how many of the derived1Obj, derived2Obj,derived3Obj is active. Should i add this in the "Base" class like a function say, GetNumber开发者_JAVA百科OfActive()?
And If the implementation is like this:
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);
};
should i calculate the numberOfActive Derived Objects in Imp Class?
THanks
One simple possibility:
NumberOfActive
should be static
in Base
. It should get incremented every time the object gets created and active is true.
You could use CRTP in conjunction with a static counter variable: Wikipedia Link
edit: some code
#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;
}
Output:
$ 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
in Configure() method you may access to a factory of Derived* objects and get the count of active obcects
精彩评论