Juraj Blaho
Juraj Blaho

Reputation: 13451

Efficient pointer to integer mapping and lookup in C++

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.

Upvotes: 2

Views: 720

Answers (4)

Bart van Ingen Schenau
Bart van Ingen Schenau

Reputation: 15768

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.

Upvotes: 6

ubik
ubik

Reputation: 605

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

class Serializable
{
};

map< Serializable *, int > integralMap;

Upvotes: 1

Tobias Langner
Tobias Langner

Reputation: 10808

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.

Upvotes: 0

Related Questions