How to initialize a static std::unordered_map of a type trait?

danijar picture danijar · Nov 3, 2013 · Viewed 25.9k times · Source

Given the following type trait, how can I initialize Fields with some std::pairs?

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

I tried using a lambda but Visual Studio says that Fields is not an entity 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 traits, which alternatives do I have to store the information in a trait? (Fields holds a SQL database structure.)

Update: The member might be also const but that shouldn't be the point.

Answer

Kerrek SB picture Kerrek SB · Nov 3, 2013

You realize you can initialize maps from braced lists?

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