Frank Wang
Frank Wang

Reputation: 920

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 this data structure in other instance. Unfortunately, it won't compile and what I found in cpp primer is:

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?

Upvotes: 1

Views: 5251

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477000

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.

Upvotes: 5

Related Questions