如何在unordered_map的键中使用std::tr1::函数对象?

How can I use a std::tr1::function object in a key to unordered_map?

本文关键字:std tr1 函数 对象 unordered map      更新时间:2023-10-16

我试图形成一个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。