0

I have declared the following map globally and trying to populate globally.

   1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList;
   2: DeviceTypeList g_DeviceTypeList;
   3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA,
   std::make_pair('B',"Single Cell Camera")));

it is showing error like error C2143: syntax error : missing ';' before '.' at line2.

1 Am I doing something wrong
2. why can't we initialize the map globally.

Vikram Ranabhatt
  • 7,268
  • 15
  • 70
  • 133

2 Answers2

4

Compiler is probably getting confused by the >> on line 1 (because it looks like a shift operator). Try inserting a space in there:

typedef std::map<unsigned short,std::pair<char,std::string> > DeviceTypeList;

[update]

See Vlad Lazarenko's comment for why this will not actually solve your problem. Easiest fix is to wrap this contraption in an object, initialize it in the constructor, then declare one at global scope. (But not if you can avoid it since globals are evil in the first place...)

Nemo
  • 70,042
  • 10
  • 116
  • 153
  • 4
    No, that won't fix it. Either initializer list from C++0x or inherited class populating base in constructor should be used. You cannot execute arbitrary functions in global scope, only constructors of global objects or initializers. –  Jun 02 '11 at 03:19
  • @Vlad what do you mean by this inherited class populating base in constructor should be used – Vikram Ranabhatt Jun 02 '11 at 03:25
  • @Vlad I think you should actually make a separate answer. – Jesse Emond Jun 02 '11 at 03:36
2

Only declarations and definitions can be in global scope, and the call to map::insert() is not one of them.

Since you're using >> in templates, your compiler must be new enough for C++0x support.

Try the C++0x initializer syntax then:

typedef std::map<unsigned short, std::pair<char,std::string>> DeviceTypeList;
DeviceTypeList g_DeviceTypeList = {
              {(unsigned short)SINGLE_CELL_CAMERA, {'B',"Single Cell Camera"}}
           };

test: https://ideone.com/t4MAZ

Although the diagnostic suggests it is MSVS, which doesn't have C++0x initializers as of 2010, so try the boost initializer syntax instead:

typedef std::map<unsigned short, std::pair<char,std::string> > DeviceTypeList;
DeviceTypeList g_DeviceTypeList =
           boost::assign::map_list_of((unsigned short)SINGLE_CELL_CAMERA,
                                       std::make_pair('B',"Single Cell Camera"));

test: https://ideone.com/KB0vV

Cubbi
  • 46,567
  • 13
  • 103
  • 169