James Franco James Franco - 1 year ago 58
C++ Question

Why does the following not work when the map is const static

Consider the following example:


static const std::map<std::string,DOG_TYPE> dogMap = {

DOG_TYPE getDogType(const std::string& dogtype)
if(dogMap.find(dogtype) != dogMap.end())
return dogMap[dogtype]; -->Does not work when std::map is constant

int main()
DOG_TYPE j = getDogType("GS");
std::cout << int(j);

In the above example the statement
return dogMap[dogtype];
returns the error

error: passing 'const std::map<std::__cxx11::basic_string<char>, DOG_TYPE>' as 'this' argument discards qualifiers [-fpermissive]
return dogMap[dogtype];

I would like to know why this happens and why cant map be
const static

Answer Source

Using operator[] on a std::map creates the object if it doesn't exist. So it's an operation that can only be performed on a map you are allowed to modify. Use find instead.