tags:

views:

75

answers:

4

I want to map pointer to integer for purpose of serialization. The pointers may be of different types and may point to polymorphic objects possibly using multiple inheritance. I need to query the map to know if the pointer is stored in it and if it is, then what is the associated integral value.

What is the correct way to do it?

The simple way of map<void*, int> that I thought of would not work because operator < is not defined for arbitrary pointers. Or is that not a problem on common systems?

Another solution would be to have a vector<void*>. But this would require to loop over all pointers stored in and I am not sure if the casting to void * would not break the operator == for objects using inheritance.

A: 

you could just do a map of unsigned int32/64 to int (depending on x86 or x64). Just cast the void* to the unsigned int and it'll happily do the comparison.

Tobias Langner
Ok, I may cast the pointer to size_t to be sure it fits, but will that not alter the equality of pointers when using inheritance?
Juraj Blaho
It is not so good idea to do this. It looks more like a hack!. If you follow this, make sure you document it so well!.
Chubsdad
please use at least intptr_t or uintptr_t, these are there for a reason.
Markus Kull
+4  A: 

You are in luck with your initial idea of using map<void*, int>.
Although you are right that operator< is not defined for pointers, the predicate used by std::map<> is std::less<> and the C++ standard requires that std::less<T*> also works for arbitrary pointers.

Quote from the C++ standard to support this ([lib.comparisons]/8):

For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not.

Bart van Ingen Schenau
I doubt this: Any reference for this
Chubsdad
Updated my answer with a supporting quote.
Bart van Ingen Schenau
+1 good to know
Alexandre C.
+1 Thanks. And I like that C**. So now we have C/C++/C**
Chubsdad
+1  A: 

Why don't you simply introduce a dummy base class for all of your serializable classes ?

class Serializable
{
};

map< Serializable *, int > integralMap;
ubik