YAKOVM
YAKOVM

Reputation: 10153

Static map initialization

I have the following code:

//MyClass.h
class MyClass {
public:
    typedef std::map<std::string, int> OpMap;
    static OpMap opMap_;     
    // (more methods)
};

//MyClass.cpp
//Init opMap_
MyClass::opMap_["x"] = 1; //compilation error

How can I (statically) initialize opMap_?

Upvotes: 25

Views: 91412

Answers (3)

docp
docp

Reputation: 337

In C++ 17 you can add inline

//MyClass.h
class MyClass {
public:
    typedef std::map<std::string, int> OpMap;
    inline static OpMap opMap_;     
    // (more methods)
};

Upvotes: 6

billz
billz

Reputation: 45450

As you are using VS2010, you need to initialize your static member in MyClass.cpp, in front of any other member function definitions. call MyClass::InitMap() if you want to initialize opMap_.

MyClass.h

class MyClass
{
public:
  MyClass(void);
  ~MyClass(void);
public:
   typedef std::map<std::string, int> OpMap;
   static OpMap opMap_;    
   static void InitMap();
};

MyClass.cpp

std::map<std::string, int> MyClass::opMap_;
MyClass::MyClass(void)
{
   InitMap(); // just sample if you want to initialize opMap_ inside MyClass constructor
}

void InitMap()
{
  MyClass::opMap_["x"] = 1;
}

Upvotes: 5

mfontanini
mfontanini

Reputation: 21910

If you're using C++11, you could use initializer lists:

//MyClass.h
class MyClass {
public:
      typedef std::map<std::string, int> OpMap;
      static OpMap opMap_;
};

//MyClass.cpp
MyClass::OpMap MyClass::opMap_ = { 
    { "x", 1 }
}; 

If you don't have access to a compiler that supports the C++11 standard, you could do the following:

//MyClass.h
class MyClass {
public:
      typedef std::map<std::string, int> OpMap;
      static OpMap opMap_;
private:
      static OpMap init_map() {
          OpMap some_map;
          some_map["x"] = 1;
          return some_map;
      }
};

//MyClass.cpp
MyClass::OpMap MyClass::opMap_ = init_map();

Upvotes: 48

Related Questions