简体   繁体   中英

C++ Error: “expression must have integral or unscoped enum type” when inserting element into std::map with operator[]

There are a lot of questions with this title but it seems neither of them is similar to my case.

I have a class member

std::map<std::string, Mode> m_stringToMode;

Mode is

enum class Mode
{
    Default, Express
};

And a I have a const method where I have inserted a new element into my map with operator[]

void LevelParser::myFunc() const
{
    std::string myStr = "myStr";
    m_stringToMode[myStr] = Mode::Express;
}

And I got 2 errors

  1. C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<std::string,Mode,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion)
  2. C++ Error: “expression must have integral or unscoped enum type”

After some time of debugging I have find out that I did stupid thing trying to modify member variable inside const member function.

So my question is. Is there any connection with error messages I have got and mistake I have did? Why compiler rising this error for this case?

I am compiling my code on Visual Studio 2013

The reason for the first error is clear: inside a const -qualified member function, all non- mutable data members of the object are accessed through a const -qualified access path. So your map is effectively const and you're trying to call a non- const function on it.

As for the exact wording of the first error: remember that std::map::operator[] is pretty much a function like any other. You're calling it with arguments of type const std::map and std::string . The compiler is saying it couldn't find any overload which could accept them. Of course, the reason is that the only existing overload requires a non- const map .

The second error you're getting can simply be ignored. The compiler is somewhat confused by the first error and prints the spurious second one.

What probably happens is that the compiler says "you cannot use map 's operator [] here, it's non- const and your map is const ." Then, since it didn't find an operator overload for [] , it interprets it as the built-in operator [] , for which at least one operand must have integral or unscoped enumeration type. Hence the second error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM