I am trying to do a simple class to unique ID conversion. I am thinking about adding a static method:
class A {
static int const *GetId() {
static int const id;
return &id;
}
};
Each class would then be identified by unique int const *. Is this guaranteed to work? Will the returned pointer really be unique? Is there any better simpler solution?
I have also thought about pointer to std::type_info:
class A {
static std::type_info const *GetId() {
return &typeid(A);
}
};
Is that better?
Edit:
I don’t need to use the id for serialization. I only want to identify a small set of base classes and I want all subclasses of some class to have the same id
As I have noticed at least MSVC 2008 or 2010 optimizes the static variable, so that the following
GetIdfunction returns same address even for different classes.Therefore address of uninitialized constant static variable may not be used for identification. The simplest fix is to just remove
const:Another solution to generate IDs, that seems to work, is to use a global function as a counter:
And then define the following method in the classes to be identified:
As the method to be defined is always the same, it may be put to a base class:
And then use a curiously recurring pattern: