I recently found the sbi version Kornel solution to be very useful. Thank you for the answers provided. However, I wanted to expand the solution so that it would be possible to easily create several types of identifiers without creating a separate pair of id_impl and id_base classes for each new type.
To do this, I configured the id_impl template and added another id_base argument. The result is encapsulated in a header file, which is included anywhere where you want to add a new identifier type:
//idtemplates.h template< class T > class GeneralID { private: GeneralID() {} static int GetNextID() { static int counter = 0; return ++counter; } template< class T, class U > friend class GeneralIDbase; }; template< class T, class U > class GeneralIDbase : private GeneralID < T > { public: static int GetID() { return ID; } private: static int ID; }; template< class T, class U > int GeneralIDbase<T, U>::ID = GetNextID();
For my application, I wanted several abstract base classes to have an identifier type associated with them. Therefore, for each instance of the GeneralIDbase template, the indicated types are: the abstract base class of the declared derived class and the declared derived class.
The following is an example of main.cpp:
//main.cpp
The output of this code
Hope this helps! Please let me know about any problems.
source share