1

I am trying to have a enum struct mapping to guarante a default value to a config value if it does not exsist and to guarante only access to "real" config values.(No std::string get)

So the Header looks like this:

enum ConfigValues
{
    LOG_LEVEL,
};

class Config
{
public:
    std::string get(const ConfigValues& key);
private:
    struct ConfigMapping
    {
        std::string configKeyString;
        std::string defaultValue;
    };

    const static std::map<ConfigValues, ConfigMapping> m_mapping;
}

And the cpp contains this:

const std::map<ConfigValues, Config::ConfigMapping> Config::m_mapping=
{
    {LOG_LEVEL, { "logLevel", "5" } },
};
std::string Config::get(const ConfigValues& key)
{
    std::string key = m_mapping[key].configKeyString; // <-- Does not work
}

But i cant access the map.

2
  • 1
    In Config::get(), both parameter and local are named key. Is that a typo in the example code or the actual problem? Maybe the actual compiler message might make things clearer. Commented Jul 28, 2015 at 8:09
  • See also stackoverflow.com/questions/5134614/c-const-map-element-access Commented Jul 28, 2015 at 8:21

1 Answer 1

6

operator[] is not const for a std::map.

Use at instead.

Before C++11 :

If you are not using C++11, you have to use find which has a const version.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah right. Didn't see that. going to accept this in some minutes when it's enabled. Thanks for that hint.
I just updated my answer for people looking for the non-C++11 answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.