How to initialize static std :: unordered_map type characteristics?

Given the following type view, how can I initialize Fields with some std::pair s?

 template <> struct ManagerDataTrait<Person> { static const std::unordered_map<std::string, std::string> Fields; // ... }; 

I tried using lambda, but Visual Studio says that Fields not an object that can be explicitly specialized.

 template <> const std::unordered_map<std::string, std::string> ManagerDataTrait<Person>::Fields = []{ std::unordered_map<std::string, std::string> fields; fields.insert(std::make_pair("height", "FLOAT")); fields.insert(std::make_pair("mass", "FLOAT")); return fields; }; 

If there is no way to use static members like this in outline, what alternatives do I need to store in the value? ( Fields contains the SQL database structure.)

Update: A member can also be const , but this should not be a point.

+7
c ++ unordered-map typetraits static-members template-specialization
source share
3 answers

Kerrek SB's answer would be the correct answer as a whole:

 const std::unordered_map<std::string, std::string> ManagerDataTrait<Person>::Fields{ { "blah", "blah" } // ... }; 

(NB no template<> because you are defining a member of a specialization, not a specialization)

But this is not supported by Visual C ++, so another alternative is to initialize the map with a function call and return the map with the desired contents from the function:

 std::unordered_map<std::string, std::string> getFields() { std::unordered_map<std::string, std::string> fields; fields["blah"] = "blah"; // ... return fields; } const std::unordered_map<std::string, std::string> ManagerDataTrait<Person>::Fields = getFields(); 

A lambda is just syntactic sugar in order to do the same, and I'm not sure it is clearer to use lambda, because the syntax is a little uglier.

+7
source share

Do you understand that you can initialize cards from copied lists?

 std::unordered_map<std::string, std::string> m { { "a", "bc" } , { "b", "xy" } // ... }; 
+17
source share

Visual C ++ now supports static initialization from copied lists, so you can do something like this:

 const std::unordered_map<std::string, std::string> ManagerDataTrait<Person>::Fields{ { "abc", "xyz" }, { "cde", "zyx" } ...}; 
0
source share

All Articles