Reputation: 336
I have some kind of container and objects can use it for storing some of their data. Each stored object should have its id, eg. MY_GL_CONTEXT, FUNNY_CONF_OBJECT etc. I would like to store these identifiers distributed across objects which will use them. Example: objects of class Model want to store there data using id MY_GL_CONTEXT.
I want to know, what kind of type should I use for these ids to avoid conflicts between classes. If I use static const int then there could happen, that Object::MY_GL_CONTEXT will have the same int value as Something::FUNNY_CONF_OBJECT so they will colide when using my container.
Thank you.
Upvotes: 1
Views: 224
Reputation: 179779
In C++, there are a few unique things.
Each object has a unique address. Cast to void*
, it can be compared for equality. Different objects have different addresses, so this makes a usuable id.
Each polymorphic type has its own run-time type information, obtainable via typeid
. This is ordered via std::type_info::before
.
Due to separate compilation, it's virtually impossible to guarantee that const int
values are unique. In fact, due to separate compilation, two .cpp files can be compiled at the same moment. How would one compiler know what int
value the other compiler will pick?
Upvotes: 2
Reputation: 24780
Create a shared .h
file and DEFINE the different values there, that way it will be easy to spot duplicated values (as long as you keep them ordered). Include that file everywhere it is needed.
// To avoid duplication
#ifndef CONSTANTS
#define CONSTANTS
#define MY_GL_CONTEXT 1
#define FUNNY_CONF_OBJECT 2
...
#endif
Upvotes: 1