How to populate a map with const reference values?

Jul 14, 2009 at 4:20am
If I have a map that looks like this:

1
2
3
4
5
6
7
8
9
10
11
#include <string>
#include <map>
#include "MyClass.hpp"

using std;
map<string,const MyClass&> lookup;

void registerInstance( string id, const MyClass& anInstance )
{
  lookup[ id ] = anInstance;   // FAILS because can't assign to a const&
}


I know I can get around this by using pointers, but is there a way to initialize a map with a reference as the value?
Last edited on Jul 14, 2009 at 5:59am
Jul 14, 2009 at 4:44am
I don't think it's possible to to use references as template types for containers. Remebmer, for example, that you can't make an array of references.

Just go ahead and use a pointer.
Last edited on Jul 14, 2009 at 4:45am
Jul 14, 2009 at 5:48am
That's what I >suspected< - thx for the confirmation.

I will do this instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include <string>
#include <map>
#include "MyClass.hpp"

using std;

static map<string,MyClass*> lookup;

void registerInstance( string id, MyClass* anInstance )
{
  lookup[ id ] = anInstance; 
}

const MyClass&
void lookupInstance( string id )
{
   return *(lookup[id]);  // being lazy: not checking for failure
}

Last edited on Jul 14, 2009 at 6:00am
Topic archived. No new replies allowed.