【发布时间】:2014-05-14 09:15:01
【问题描述】:
更新以粗体
我正在为函数指针表编写一个哈希函数函数指针和函数表的结构不能修改(即它们已发布给第三方)。基于Can std::hash be used to hash function pointers?,std::hash 可用于函数指针。采用它,它产生以下解决方案。
这个解决方案的繁琐之处在于,每次我们向 FuncPointers 结构添加新的 API 时,我们都必须修改哈希特化以添加相应的更改(即 hashFunc(hashedValue, pFuncs->func3) )。
我想知道是否有更好的方法来实现函数指针的这种散列,从而可以避免对散列特化的持续修改?
typedef void (*func_type1) (int);
typedef void (*func_type2) (double);
typedef struct FuncPointers
{
func_type1 func1;
func_type2 func2;
...
} FuncPointers;
template <typename T> void hashFunc (size_t & HashedValue, T funcPointer)
{
std::hash<T> hash;
HashedValue ^= hash(funcPointer); // the XOR operator is randomly picked
}
namespace std
{
template<> struct hash<FuncPointers>
{
size_t operator()(FuncPointers *pFuncs)
{
size_t hashedValue = 0;
hashFunc(hashedValue, pFuncs->func1);
hashFunc(hashedValue, pFuncs->func2);
...
return hashedValue;
}
};
}
【问题讨论】:
-
这里是符合标准的
std::tuple的解决方案:stackoverflow.com/a/7115547/1774667(答案的第二部分,第一部分违反了C++11标准)