Search code examples
c++templatesinheritancertti

Initializing static const in a class that extends a template


Consider this pseudocode:

class Foo {
public:
    virtual int getID() const = 0;
}

template<typename T>
class Blah : public Foo {
public:
    T data;
    static const int ID;  //static ID
    int getID() const { return Blah<T>::ID; }  //instance returns the ID
}

class Dude : public Blah<int> {
}
int Dude::ID = 10;  //I want to define Blah<int>::ID here, but how?

int receive(const Foo& foo) {
    if(foo.getID() == Dude::ID) {
        cout << "Received a Dude" << endl;
    }
}

This piece of code fails to compile because ISO C++ does not permit the ID in the Blah template to be defined as the ID in the Dude class. I understand why because I could have multiple classes that extend a Blah<int>.

I understand if I put template<typename T> int Blah<T>::ID = 10' in the Blah<T> impl that it will work...but that isn't what I want...I want the derived class to define the ID...

Do I have to push the ID and getID() into the derived class? I guess ultimately I'm interested in some RTTI so I can process the Foo appropriately. If anyone has a better pattern, I'm all ears.

EDIT In response to some of the comments...I would like to uniquely identify classes that derive from Foo via some ID so I can compare the runtime id of some Foo object to a specific class id.

Thanks!


Solution

  • I found this answer that does exactly what I'm after...sorry if my question was confusing.

    in C++, how to use a singleton to ensure that each class has a unique integral ID?