James Franco James Franco - 3 months ago 6
C++ Question

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

Consider the following example:

enum class DOG_TYPE {SHEPHARD, COLLIE,UNKNOWN};

static const std::map<std::string,DOG_TYPE> dogMap = {
{"GS",DOG_TYPE::SHEPHARD}
};


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

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.

Comments