packetie
packetie

Reputation: 5069

Compile error when defining a hash class

The following code snippet gave error on g++ (ver 4.73). There must be something silly I did.

$g++ -std=c++11 te2d.cc
te2d.cc:61:7: error: ‘MyMacHash’ is not a template
te2d.cc: In member function ‘size_t MyMacHash::operator()(const cMacAddr&) const’:
te2d.cc:63:83: error: passing ‘const cMacAddr’ as ‘this’ argument of ‘long int cMacAddr::toLong()’ discards qualifiers [-fpermissive]

Source code

#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <malloc.h>
#include <unordered_map>
#include <string>

using namespace std;

typedef unsigned char uchar;

class cMacAddr {
public:
    uchar addr[6];
    cMacAddr(uchar *newAddr) { for (int i=0; i<6; i++) addr[i] = newAddr[i];}
    cMacAddr(const char *newAddr) { for (int i=0; i<6; i++) addr[i] = newAddr[i];}
    bool operator == (uchar *newAddr) {
        for (int i=0; i<6; i++) if (addr[i] != newAddr[i]) return false;  
        return true;
    }
    bool operator == (unsigned long newAddr) {
        unsigned long tmp = 0;
        for (int i=0; i<6; i++) tmp = (tmp << 8) + addr[i];
        return tmp == newAddr;
    }
    bool operator == (cMacAddr &m) {
        for (int i=0; i<6; i++) if (addr[i] != m.addr[i]) return false;  
        return true;
    }
    bool operator != (unsigned long newAddr) {
        unsigned long tmp = 0;
        for (int i=0; i<6; i++) tmp = (tmp << 8) + addr[i];
        return tmp != newAddr;
    }
    operator long () {
        return this->toLong();
    }
    long toLong() {
        unsigned long tmp = 0;
        for (int i=0; i<6; i++) tmp = (tmp << 8) + addr[i];
        return tmp; 
    }
    string toString() {
        char buf[30];
        int i;
        int offset = 0;
        for (i=0; i<6; i++) {
            if (i) { buf[offset] = ':'; offset ++; }
            offset += sprintf(&buf[offset], "%02x", addr[i]);
        }
        return string(&buf[0]);
    }
    uchar operator [] (int id) { return addr[id]; } 
    uchar * ptr() { return &addr[0];}
};

class MyMacHash {
public:
  size_t operator()(const cMacAddr& m) const { return std::hash<long>() (m.toLong()); }
};
typedef std::unordered_map< cMacAddr, long, MyMacHash > m2imap; 

int main (int argc, char *argv[]) {
    m2imap x;

    return 0;
}

Upvotes: 1

Views: 97

Answers (1)

yiding
yiding

Reputation: 3592

This error:

te2d.cc: In member function ‘size_t MyMacHash::operator()(const cMacAddr&) const’:
te2d.cc:63:83: error: passing ‘const cMacAddr’ as ‘this’ argument of ‘long int cMacAddr::toLong()’ discards qualifiers [-fpermissive]

refers to the fact that your hash functor takes in a const cMacAddr& m, but you call m.toLong(), which is not a const function.

You should declare toLong as const, i.e

long toLong() const {

Upvotes: 3

Related Questions