Frank Wang Frank Wang - 1 month ago 20
C++ Question

Initialization of static const member map<> in class definition

I'm gonna to have a const std::map in my class, and I want it be static to reuse the data structure. Unfortunately, it won't compile due to this:


However, we can provide in-class initializers for static members that have const integral type and must do so for static members that
are constexprs of literal type (Primer 5th).


My code is looks like :

clase worker {
//.....
private :
//.....
static map<string, string> const map_{...};
}


So, is there a OOP technique to reuse this data structure, assuming that we have tens of worker and map_ is big?

Answer

It seems you're just unfamiliar with the relevant piece of C++ syntax for class members:

class worker
{
private:
    static const std::map<std::string, std::string> m_;
};

const std::map<std::string, std::string> worker::m_ = {
  { "foo", "bar" },
  { "abc", "def" },
};

The member definition usually lives in a separate .cpp file, so that its containing translation unit only appears once in the link.