1

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?

lapots
  • 12,553
  • 32
  • 121
  • 242
  • By the way, you should not scope your template argument as `core::Object`, just `Object` because it is already in the `core` namespace. – Cory Kramer Jul 17 '15 at 19:31

1 Answers1

1

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.

Community
  • 1
  • 1
Barry
  • 286,269
  • 29
  • 621
  • 977