Is there a way to create a hash of hashes in C++?
Effectively I am trying to do what you can do in Perl but only in C++. Here is an example of Perl code I would like to have happen in C++
%hash = (
gameobject1 => {
position => {
x_loc => 43,
y_loc => 59,
}
rect_size => {
width => 5,
height => 3,
}
collidable => 1,
sounds => {
attack => "player_attack.ogg",
jump => "player_jump1.ogg",
jump_random => [qw/player_jump1.ogg player_jump2.ogg player_jump3.ogg/]
}
},
gameobject2 => {
position => {
x_loc => 24,
y_loc => 72,
}
rect_size => {
width => 2,
height => 4,
}
sounds => {
attack => "goblin_attack.ogg",
}
items => [qw/sword helmet boots/]
},
);
The thing to note is the hashes with in gameobjects can exist or not... i.e. position might exist in gameobject1 but may not exist for gameobject35.
Any ideas?
Perl hashes let you use anything for values. C++ being a statically typed language, it won't let you do that: you have to specify exactly what type you want the values in the hash (in C++ lingo, the map) to have.
Here's possible solution with C++11 and boost, with some strong typing thrown in :)
If you really want something like a Perl hash of Perl hashes, you can use
std::map<std::string, boost::any>
to get the ability to store anything in the map. However, this requires you to test for the types of every value before obtaining it from the map. If only a certain set of types is possible, you can use something more strongly-typed thanboost::any
, likeboost::variant
.