Advertisement

Automatically generate unique ID's at compile time

Started by August 09, 2004 11:03 AM
15 comments, last by stodge 20 years, 6 months ago
Hi there,

I have also thought of the problem with an int overflow,
so basically what I do is keep a list of UIDs that were used
before and take them first.

When an object is deallocated it returns its UID to the system.

class UIDGenerator{private:	std::list<int> returnedIDs;	int highestID;public:	int GetUniqueID();	void ReturnUniqueID(int id);};int UIDGenerator::GetUniqueID(){    if (retunedIDs.empty())    {       return highestID++;    }    else    {       int id = retunedIDs.back();       retunedIDs.pop_back();       return id;    }}void UIDGenerator::ReturnUniqueID(int id){    retunedIDs.push_back(id);}



****EDIT:
Oh sorry, I didn't read the other posts.
So you're looking for something like a ClassID to identify
a class and not an ID to identify actual instances of the class.
hm........ :)
To generate unique identifiers for your classes you can define your class like this:

(put the id() function in every class that should have its own identifier)

class A{	public:	static unsigned id() { return (unsigned)id; }};


and then access the id by calling

A::id();


This will even work for templates, since whenever the template is instanciated a new function is created. However, there is a drawback when using derived classes, since they inherit the id of their parent.


Another possible solution might be to play around with __FILE__ and __LINE__:

#define XSTR(s) STR(s)#define STR(s) #s#define CLASS_ID __FILE__ "_" XSTR(__LINE__)class B{	public:	static char* getID() { return CLASS_ID ; }};


and get the id by calling

B::getID();


Advertisement
If you're only building on Windows look at the __COUNTER__ macro.
These may help:
Why Pluggable Factories Rock My Multiplayer World
Creating a Generic Object Factory
I like the sound of GUIDs.
---------------------http://www.stodge.net

This topic is closed to new replies.

Advertisement