Sign in to follow this  
CProgrammer

arbitrary types list

Recommended Posts

I am saving data in a hash map. Sadly I need to be able to save pointers, ints and floats. Now what would the best way be to define the list structures used in the hash map so that they can be holding any one of the three. I looked into templates but I am not sure how the links to the next list element will work since it doesnt know what type the next element uses. -CProgrammer

Share this post


Link to post
Share on other sites
Quote:
Original post by DrEvil
For primitive types like that I'd go with a simple union.


Indeed. Though I'd first look to make really sure that such a construct was necessary. It's almost always a sign of problematic design which will only bite you in the ass elsewhere and/or later.

Share this post


Link to post
Share on other sites
Quote:
Original post by CProgrammer
Hm, hadnt thought of unions. Good idea. However would that cause endiness problems on other systems? Probably since not all the types are necessarily of the same size.


No, union is language construct. Compiler then handles it in platform specific manner.

And if you intend to serialize things, then you need to handle those elsewhere in the first place.

Share this post


Link to post
Share on other sites
Quote:
Original post by CProgrammer
Thanks guys!
Ill go with the union construct.
Before committing yourself to using a union, I'd recommend taking a look at Boost.Variant, as suggested earlier by Spoonbender. Reasons you might prefer variant include (but are not limited to):

1. variant interoperates with C++ stream objects in a natural way.

2. variant knows the type of its held object. With a union, you have to manage this information separately.

3. A union can only hold POD types.

4. There's nothing to prevent you from accessing the 'wrong' member of a union and getting garbage as a result (as such, storing pointers in a union is a particularly bad idea). variant, on the other hand, allows for safe access to its held value.

5. Although variant has some additional syntactical overhead in comparison with a union, its use would probably lead to simpler code overall (due to less error-checking and fewer 'type queries').

Having said all that, since I don't actually know what you're doing I can't say for sure that variant is the right solution. However, based on the information you've provided it seems like it would be preferable to using a union.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this