Skip to main content
gamedev.net
🔒 Locked

arbitrary types list

Started by CProgrammer 6 replies 1k views
Original Post
CProgrammer
CProgrammer
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
Telastyn
Telastyn
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.
CProgrammer
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.
Antheus
Antheus
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.
CProgrammer
CProgrammer
Thanks guys!
Ill go with the union construct.
Zakwayda
Zakwayda
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.