lapots
lapots

Reputation: 13415

symbol hash could not be resolved

I have such class

#ifndef _OBJECT_H_
#define _OBJECT_H_

#include <iostream>
#include <functional>

namespace core {

class Object {
protected:
    template <>
    struct std::hash<core::Object>
    {
        size_t operator()(const core::Object &x) const = 0;
    };
public:
    virtual Object* clone() = 0;
    virtual int hashCode() = 0;
    virtual std::string getClass() = 0;
    virtual ~Object();
};

}


#endif

I want to force all inherited classes to implemented hash calculation and provide ability to get hashcode using implemented method for overriding () in hash struct.

However my compiler shows Symbol 'hash' could not be resolved error. I am using Eclipse c++ with CDT plugin and TDM gcc 5.1.0. What's the problem?

Upvotes: 1

Views: 378

Answers (1)

Barry
Barry

Reputation: 303676

If you want to add an explicit specialization to std::hash for Object, the correct way to do it is this:

namespace core {
    class Object { ... };
}

namespace std {
    template <>
    struct hash<core::Object> {
        size_t operator()(const core::Object& x) const {
            return x.hashCode(); // though to make this work,
                                 // hashCode() should be const
        }
    };
}

The explicit specialization must be in namespace scope - in std's scope, specifically. And you can only make virtual functions pure (= 0), this one shouldn't be virtual or pure.

Side-note, your _OBJECT_H include guard is a reserved identifier. You should choose another one.

Upvotes: 1

Related Questions