可以使用std :: hash来哈希函数指针吗? [英] Can std::hash be used to hash function pointers?

查看:164
本文介绍了可以使用std :: hash来哈希函数指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11 std :: hash 类型可以用于哈希函数指针吗?有一个 hash 部分专门化定义为

Can the C++11 std::hash type be used to hash function pointers? There is a hash partial specialization defined as

template <typename T> struct hash<T*>;

但是由于函数指针与C ++中的其他指针类型不同(例如, void * ),我不确定是否可以安全地使用类型 int(*)() void(*)(int,int)

but since function pointers are different from other pointer types in C++ (e.g. they can't be cast to void*), I'm not sure whether it is safe to use it for types like int(*)() or void(*)(int, int).

谢谢!

推荐答案

很好的问题。我不知道答案肯定,我很高兴推迟任何人比我更了解,但我的想法是,即使函数指针与数据指针不一样,它们仍然是指针:所以 std :: hash< T *> 应该应用部分专业化。

Great question. I don't know the answer for sure, and I'm happy to defer to anyone with better knowledge than me, but my thinking is that even though function pointers aren't the same as data pointers, they are pointers nonetheless: so the std::hash<T*> partial specialisation should be applied.

即使使用g ++ 4.8.1和clang 3.3中的 -pendantic ,也可以正常工作:

For what it's worth, the following compiles without warnings even with -pendantic in g++ 4.8.1 and clang 3.3, and works as expected:

#include <functional>
#include <iostream>

void func1(int) {}
void func2(int) {}

int main()
{
    typedef void (*func_type) (int);

    std::hash<func_type> hash;

    std::cout << hash(func1) << std::endl;
    std::cout << hash(func2) << std::endl;

}



如果任何人有任何参考标准来支持这一点。

I'd be really interested if anyone has any references to the standard to back this up though.

这篇关于可以使用std :: hash来哈希函数指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆