如何在unordered_map的键中使用std::tr1::函数对象?
How can I use a std::tr1::function object in a key to unordered_map?
我试图形成一个std::tr1::unordered_map,其中键类型是一个包含回调函数的结构体,为此我使用std::tr1::函数。我遇到了两个问题:1)函数对象似乎不像Boost那样具有可比性。函数文档表明;2)我不知道如何实现哈希函数,因为我不能从函数对象中获得一个常规的函数指针(或其他我可以用于哈希的东西)。
下面是示例代码:#include <boost/functional/hash.hpp>
#include <boost/tr1/functional.hpp>
#include <boost/tr1/unordered_map.hpp>
#include <iostream>
int f(int) {}
typedef std::tr1::function<int(int)> callback;
struct Record
{
callback func;
// More members...
// Requirements for unordered_map key.
friend bool operator==(Record const & lhs, Record const & rhs)
{ return lhs.func == rhs.func; } // error: ambiguous
friend std::size_t hash_value(Record const & arg)
{ return boost::hash<void *>(arg.func.get()); } // error: no member get()
};
int main()
{
std::tr1::unordered_map<Record, int> map;
Record a = {f};
map[a] = 0;
return 0;
}
下面是第一个错误的一些细节:
test.cpp: In function bool operator==(const Record&, const Record&):
test.cpp:16: error: ambiguous overload for operator== in lhs->Record::func == rhs->Record::func
test.cpp:16: note: candidates are: operator==(void (boost::function1<int, int>::dummy::*)(), void (boost::function1<int, int>::dummy::*)()) <built-in>
<root>/boost/function/function_template.hpp:1024: note: void boost::operator==(const boost::function1<R, T0>&, const boost::function1<R, T0>&) [with R = int, T0 = int]
第二个错误,显然没有函数<…>::get成员,但是我应该用什么代替呢?
我使用Boost版本1.42和g++ 4.2.2。谢谢你的帮助。
更新tr1::function对象是可哈希的(例如,使用boost::hash),但不具有可比性。如果您想在散列键中使用函数,请重新考虑方法或寻找解决方案。似乎TR1特别要求
template<class Function2> bool operator==(const function<Function2>&);
template<class Function2> bool operator!=(const function<Function2>&);
仍然未定义(3.7.2.6),所以至少你必须找到另一种方法来获得相等。此外,我也没有在论文中找到任何关于get()
成员方法的参考。
我可以回答我自己关于hash_value的问题。这是使用tr1::函数调用boost::hash的正确方法:
friend std::size_t hash_value(Record const & arg)
{
boost::hash<callback> hasher;
return hasher(arg.func);
}
这里和这里讨论了一些使用function::target
的想法。您可能还需要考虑Boost。
相关文章:
- 如何修复以下错误"no match for call to '(std::tr1::shared_ptr<_iobuf*>) (FILE*&)'"
- std :: tr1 :: shared_ptr throw bad_alloc,也是一个好主意
- std::tr1::函数和它接受的模板值
- c value_type对于std :: tr1不起作用:std :: map中的元组
- 擦除 std::tr1::unordered_map 中的元素
- GHashTable vs std::tr1::unordered_map
- boost::function 和 std::tr1::function 之间是否有重要的区别需要了解
- std::tr1::函数为VS2008 SP1中的x64配置提供链接错误
- std::tr1::shared_ptr and dynamic_cast
- boost::hash/std::tr1::hash 不为复制的 const char* 返回相同的哈希
- 将 std::tr1 导入 std - 合法吗?它是否提高了便携性
- G++4.8 中对"std::tr1::__detail::__prime_list"的未定义引用
- 使用 std::tr1::bind 或 std::tr1::mem_fn 时,可以使用 std::not1 的替代方案
- visual c++ std::tr1::hash::operator() undefined?
- 处理std::tr1::shared_ptr向量的约定
- 使用boost序列化、std::tr1::unordered_map和自定义键的奇怪行为
- std::tr1::将各种类型的函数对象存储在公共容器中
- std::tr1::函数赋值和绑定
- 使用std::tr1::sharedptr作为引用计数的内部机制
- Boost::shared_ptr vs std::tr1::shared_ptr在多操作系统上的编译