quetzalfir quetzalfir - 2 months ago 7
C++ Question

C++ Vector of template class, Polymorphism

Every time that I create a object, I store the pointer of that object in a vector, which is a static member of the class of the object, in order to monitor its state, something like this:

class A {
private:
static std::vector<A *> as;
STATE state = NONE; //<- enum
void doSomething();

public:
A() {
as.push_back(this);
}

static void monitor() {
auto end = as.end();

for (auto obj = as.begin(); obj != end; obj++) {
switch ((*obj)->state) {
//process it
(*obj)->doSomething();
}
}
}
}

//// recurrent call in other part of the program or even in other thread
A::monitor();


The above code is obviously incomplete, lacks an appropriately destructor, to remove the pointer of the vector that is being deleted.

the problem now is that I have to do the same with a template class

template <typename T>
class A {

void doSomething(); //<--independent, no template
....
}


Is there any way to do the same?, applying the independent type method "doSomething()" for every object?

If the function "doSomething()" was dependent type, there would be a way to accomplish the same?

Answer

You can do the same:

template <typename T>
class A {
private:
    static std::vector<A<T>*> as;
    STATE state = NONE; //<- enum
    void doSomething()

public:
    A() { as.push_back(this); }

    static void monitor() {
        auto end = as.end();

        for (auto obj = as.begin(); obj != end; obj++) {
            switch ((*obj)->state) {
                //process it
                (*obj)->doSomething();
            }
        }
    }
}

template <typename T>
std::vector<A<T>*> as;

You just have to call

A<MyType>::monitor();