0

I have the same problem as here, here or here, except I have put const for the argument and the function:

#include <unordered_map>
#include <functional>

namespace zzz {

struct identity_t {
    static const int ID_SIZE = 5;
    static const int LSB = 4; // = ID_SIZE - 1
    unsigned char id[ID_SIZE];
    inline bool operator< (const identity_t& rhs) const {
        for (int i = 0; i < ID_SIZE; i++) if (id[i] != rhs.id[i]) return (id[i] < rhs.id[i]);
        return false; // equal
    }
    unsigned char operator[] (const int& i) {return id[i];}
};

class hash_identity_t {
public:
    long operator()(const identity_t& x) const {
        return (long) x[identity_t::LSB];
    }
};

class equal_to_identity_t {
public:
     bool operator()(const identity_t& lhs, const identity_t& rhs) const {
         for (int i = 0; i < identity_t::ID_SIZE; i++) if (lhs[i] != rhs[i]) return false;
          return true;
     }
};

But I have the same compilation error:

error: passing 'const zzz::identity_t' as 'this' argument of 'unsigned char zzz::identity_t::operator[](const int&)' discards qualifiers [-fpermissive]
Community
  • 1
  • 1
lalebarde
  • 1,684
  • 1
  • 21
  • 36
  • You have not put const for the function... – Oliver Charlesworth Jan 04 '14 at 11:51
  • 2
    Well you put `const` on one of the functions, but the error is telling you you need it on `operator[]` too. This suggests to me that you don't really know why you're putting `const` on the functions. Do you? – Joseph Mansfield Jan 04 '14 at 11:57
  • After reading your remarks, it looks obvious. But at first hand, interpreting error messages is not. In my understanding, const for an argument means the function won't modify it, but const for a method is not so clear to me. – lalebarde Jan 04 '14 at 21:31

2 Answers2

5

You're trying to call a non-const function(identity_t::operator[]) on a const parameter in const function long hash_identity_t::operator( const identity_t& x ).

Make identity_t::operator[] constant.

//--------------------------------------vvvvv
unsigned char operator[] (const int& i) const {return id[i];}
BanksySan
  • 27,362
  • 33
  • 117
  • 216
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
0

use at() method of std::map.

const mapped_type & at (const key_type &__k) const 
ideawu
  • 2,287
  • 1
  • 23
  • 28