A better way to define class id

Hello.
Currently I define class ids as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Base {
public:
    static unsigned typeId() { return s_typeId; }

protected:
    static unsigned s_typeCounter;
    static unsigned s_typeId;
}

unsigned Base::s_typeCounter{0};
unsigned Base::s_typeId{s_typeCounter++};

class A : public Base {
public:
    static unsigned typeId() { return s_typeId; }

private:
    static unsigned s_typeId;
}

unsigned A::s_typeId{s_typeCounter++};

But defining class ids in such a way is a bother. So maybe there's a better way to define class ids considering that ids must be unique among multiple translation units (__COUNTER__ won't do)?

Update:
RTTI is not available.
Last edited on
JLBorges
Oh, forgot to mention. RTTI is not available.
CRTP?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <iostream>

struct counter { 
  static int c;
};

int counter::c = 0;

template <typename Derived>
struct has_counter: counter {
    static int id()
    { static int c = counter::c++; return c; }    
};

class A: public has_counter<A> {};
class B: public has_counter<B> {};

int main() { 
    std::cout << A::id() << '\n' << B::id() << '\n';    
}
mbozzi
This looks good. Thanks.
Topic archived. No new replies allowed.