views:

128

answers:

3

I have a template that creates a unique identifier for each type it is instanced. Here's a streamlined version of the template:

template <typename T>
class arType {
  static const arType Id; // this will be unique for every instantiation of arType<>.
}

// Address of Id is used for identification.
#define PA_TYPE_TAG(T) (&arType<T >::Id)

This works when you have an executable made purely of static libraries. Unfortunately we're moving to an executable made up of dlls. Each dlls could potentially have its own copy of Id for a type.

One obvious solution is to explicitly instantiate all instances of arType. Unfortunately this is cumbersome, and I'd like to ask if anyone can propose a better solution?

A: 

Yes, and it's simpler than you think:

template<...> class withAnID {
    static void idFunction(){};
}

Usage:

&withAnID<...>::idFunction;

Since each instance of the template gets it's own assembly, each function has a unique (sortable!) address, and you can just use that to identify them.

Narfanator
Across DLL's? I don't think so. This is no different than the solution the OP has.
GMan
Thanks Narfanator, but GMan is correct. I'm looking for solution that works across DLLs.
Michael Kelley
A: 

Well I think that the only way is to program a method processing Ids that take into account the DLL problem :)

I mean that if you can compute the global type ID as "DLL Id" + "DLL local type Id" you have what you want. I think it might be feasible if you manage the DLL loading part or if the OS give you callbacks to manage that. If you can set a unique ID in a DLL bound object you are done ;-)

I'm no expert in windows DLL management, but I remember that there is something like "on_dll_load" callback thing that might do the trick. Any DLL management expert ?

Just my 2 cents ...

neuro
+1  A: 

Return a std::type_info object from a function on each object and use operator == on the result. You can sort them by using the before() function which returns the collation order.

It's specifically designed to do what you want. You could wrap it in an opaque "id" type with an operator< if you wanted to hide how it works underneath.

http://www.cplusplus.com/reference/std/typeinfo/type_info/

Matthew Herrmann
This is what I ended up doing, and it seemed to do the job. Not as quick as a pointer check, but oh well...
Michael Kelley