Is it possible to use a reference as the value in a standard map container in C++?
If not - why not?
Example declaration:
map<int, SomeStruct&> map_num_to_struct;
Example usage:
...
SomeStruct* some_struct = new SomeStruct();
map_num_to_struct[3] = *some_struct;
map_num_to_struct[3].some_field = 14.3;
cout<<some_struct.some_field;
...
I would expect to see 14.3 printed...
No. STL container value types need to be assignable. References are not assignable. (You cannot assign them a different object to reference.)
No, it's not. You can use pointers as the value type, though.
I don't think so, references are supposed to be treated like constant pointers to a certain element if I remember correctly. But you could just use pointers to the same effect.
No, you can't use references but you can use pointers. You seem to be mixing up both in your example. Try:
map<int, SomeStruct *> map_num_to_struct;
SomeStruct* some_struct = new SomeStruct();
map_num_to_struct[3] = some_struct;
map_num_to_struct[3]->some_field = 14.3;
cout<<some_struct->some_field;
Value types must be assignable, and references are not.
Anyway you can use a tr1 reference_wrapper
.