Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a static member unordered_map via operator[]

Tags:

c++

Being quite green with C++, I ran into behavior I don't quite understand, and haven't been able to find an explanation even with intense googling, so I was hoping someone could explain what exactly is wrong here.

// test.h

#include <unordered_map>

typedef std::unordered_map<int, int> test_type;

class test
{
public:
    static const test_type tmap;
};


// test.cpp

#include "test.h"

const test_type test::tmap = {
    { 1, 1 }
};


// main.cpp

#include "test.h"

int main()
{   
   // Attempt 1: access key via operator[]
   std::cout << test::tmap[1];

   // Attempt 2: access key via at()
   std::cout << test::tmap.at(1);

   return 0;
}

If I have Attempt 1 in my code, Visual Studio's compiler insists I'm using a binary [ operator that hasn't been defined, but that doesn't really make sense to me because as far as I know there is no binary [ operator, (braces are always unary, right?).

So, why doesn't Attempt 1 work?

like image 368
Schlaus Avatar asked Feb 10 '23 21:02

Schlaus


1 Answers

The problem is std::unordered_map::operator[] is not const, because it inserts the specified key to the map if it doesn't already exist. Since it is not const you cannot use it with a const object. std::unordered_map::at does have a const overload so it compiles. You either need to make test non-const or just use the at() function.

like image 186
NathanOliver Avatar answered Feb 13 '23 03:02

NathanOliver