Access static member unordered_map using operator []

Being pretty green with C ++, I came across behavior that I donโ€™t quite understand, and could not find an explanation even with an intensive search on Google, so I was hoping that someone could explain what was definitely 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 code 1 in my code, the Visual Studio compiler insists that I use a binary operator [that has not been defined, but that makes no sense to me, since, as far as I know, it is not a binary operator [, (brackets always unary, right?).

So why does attempt 1 fail?

+4
source share
1 answer

std::unordered_map::operator[] const, , , const, const. std::unordered_map::at const, . test const, at().

+7

All Articles