比较std :: function<>

时间:2011-05-01 07:16:52

标签: c++ c++11 tr1

是否有可能以某种方式比较两个std::tr1::function<>个对象?如果我有一组function<void(int,float)>个对象并想要添加和删除事件处理程序,该怎么办?添加是微不足道的,但找到要删除的那个似乎是不可能的。

2 个答案:

答案 0 :(得分:7)

无法完成,简单地说。 std::function(在所有迭代中,包括boost::functionstd::tr1::function)不支持operator==

答案 1 :(得分:3)

根据以下链接中Stack Overflow的信息,只有将std :: function对象包装在自己的类中才有可能。

std::vector of std::function

通过使用包装器类,您可以测试两个包装的s​​td :: function指针是否相等,但这并不能告诉您有关std :: function包装的内容。因此,改变您的设计可能是一种更好的方法。

编辑:我回来展示我解决了一个非常类似问题的方式。

0)Typedef简洁。

    using std::placeholders;
    typedef std::function < void ( int, float ) > some_func;
    typedef std::pair < intptr_t, intptr_t > method_hash;
  1. 通过绑定指向方法或函数的指针来编写std :: function对象的集合。在静态函数中执行此操作时,请省略some_object_ptr。

    some_func some_method ( std::bind ( some_method_ptr, 
                                        some_object_ptr, _1, _2 ) 
    
  2. 使用std :: reinterpret_cast&lt; intptr_t&gt;为您的函数创建一个唯一的哈希值,并将它与std :: pair一起用于方法。

     method_hash pairID ( reinterpret_cast < intptr_t > ( some_object_ptr ), 
                          reinterpret_cast < intptr_t > ( some_method_ptr ) );
    
  3. 现在您的pairID可以存储在矢量或其他容器/数组中。请务必保持索引已对齐,以便散列始终对应于正确的std :: function对象,然后您可以使用find()获取其位置和距离()的迭代器以将迭代器转换为所需索引。

  4. 请注意,每次生成容器时都必须执行此操作。由于它基于指针,因此哈希将在程序的不同运行中发生变化。