将std :: hash专门用于派生类

时间:2014-02-20 07:10:42

标签: c++11 gcc hash template-specialization stdhash

我有一个抽象基类Hashable,可以散列的类派生自。我现在想将std::hash扩展到源自Hashable

的所有类

以下代码应该就是这样做的。

#include <functional>
#include <type_traits>
#include <iostream>

class Hashable {
public:
    virtual ~Hashable() {}
    virtual std::size_t Hash() const =0;
};

class Derived : public Hashable {
public:
    std::size_t Hash() const {
        return 0;
    }
};

// Specialization of std::hash to operate on Hashable or any class derived from
// Hashable.
namespace std {
template<class C>
struct hash {
  typename std::enable_if<std::is_base_of<Hashable, C>::value, std::size_t>::type
  operator()(const C& object) const {
    return object.Hash();
  }
};
}

int main(int, char**) {
    std::hash<Derived> hasher;
    Derived d;
    std::cout << hasher(d) << std::endl;

    return 0;
}

上面的代码与gcc 4.8.1完全一样,但是当我尝试使用gcc 4.7.2编译它时,我得到以下内容:

$ g++ -std=c++11 -o test test_hash.cpp
test_hash.cpp:22:8: error: redefinition of ‘struct std::hash<_Tp>’
In file included from /usr/include/c++/4.7/functional:59:0,
                 from test_hash.cpp:1:
/usr/include/c++/4.7/bits/functional_hash.h:58:12: error: previous definition of ‘struct std::hash<_Tp>’
/usr/include/c++/4.7/bits/functional_hash.h: In instantiation of ‘struct  std::hash<Derived>’:
test_hash.cpp:31:24:   required from here
/usr/include/c++/4.7/bits/functional_hash.h:60:7: error: static assertion failed:  std::hash is not specialized for this type

是否有人想到一种方法可以使std::hash的这种专业化适用于使用gcc 4.7.2从Hashable派生的任何类?

1 个答案:

答案 0 :(得分:2)

似乎没有正确的方法来做我想做的事情。我决定使用以下宏为每个派生类编写单独的特化:

// macro to conveniently define specialization for a class derived from Hashable
#define DEFINE_STD_HASH_SPECIALIZATION(hashable)                               \
namespace std {                                                                \
template<>                                                                     \
struct hash<hashable> {                                                        \
  std::size_t operator()(const hashable& object) const {                       \
    return object.Hash();                                                      \
  }                                                                            \
};                                                                             \
}

然后

// specialization of std::hash for Derived
DEFINE_STD_HASH_SPECIALIZATION(Derived);