I have a bunch of C++ classes.
I want each class to have something like:
static int unique_id;
All instances of a same class should have the same unique_id; different classes should have different unique_id's.
The simplest way to do this appears to be threading a singleton through the classes.
However, I don't know what's called when for static class members / things that happen before main.
(1) if you have a solution that does not involve using singleton, that's fine too
(2) if you have a solution that gives me a :
int unique_id();
that is fine too.
Thanks!
Actually that's very similar to RTTI. To achieve (2), C++'s buildin RTTI can be exploited. Call
typeid
on*this
, and take the address of the typeinfo as unique ID.Conss: a) IDs aren't be fixed (recompile would change them), and b) the information is only available given an instance of the class, c) it's ugly.
Why do you want this?
C++ has this already built in.
You can use the
typeid
operator to return atype_info
class. Thetype_info:name()
will return the (unique) name of the class.First, why? In any case, you can manually set the IDs easily:
Then
Of course, you'll have to manually keep track of the IDs for each class; at this point, I'll ask the original question: why?
Have a class that increments it's ID on each creation. Then use that class as a static field in each object that is supposed to have an ID.
I have recently found sbi's version of Kornel's solution to be very useful. Thank you both for providing your answers. However, I wanted to extend the solution further so that several types of IDs can be easily created without creating a separate pair of id_impl and id_base classes for each new type.
To do this I templated the id_impl class, and added another argument to the id_base. The result is encapsulated in a header file that is included anywhere one wants to add a new ID type:
For my application I wanted several abstract base classes to have an ID type associated with them. So for each instance of the GeneralIDbase template the types specified are: the abstract base class of the derived class being declared, and the derived class being declared.
The following main.cpp is an example:
The output of this code is
I hope this helps! Please let me know of any issues.
Building on Kornel's solution:
Use it like this: