比较std :: function <>

Mar*_*son 6 c++ tr1 c++11

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

Pup*_*ppy 7

不能做,简单地说.std::function(在所有迭代中,包括boost::functionstd::tr1::function)都不支持operator==.


JPH*_*ord 5

根据以下链接中来自 Stack Overflow 的信息,这是可能的,但前提是您将 std::function 对象包装在其自己的类中。

std::function 的 std::vector

通过使用包装类,您可以测试两个包装的 std::function 指针是否相等,但这并不能告诉您有关 std::function 包装什么的任何信息。所以,改变你的设计可能是一个更好的方法。

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

0) 简洁的类型定义。

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

    some_func some_method ( std::bind ( some_method_ptr, 
                                        some_object_ptr, _1, _2 ) 
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用 std::reinterpret_cast < intptr_t > 为您的函数创建唯一的散列,并将其与 std::pair 一起用于方法。

     method_hash pairID ( reinterpret_cast < intptr_t > ( some_object_ptr ), 
                          reinterpret_cast < intptr_t > ( some_method_ptr ) );
    
    Run Code Online (Sandbox Code Playgroud)
  3. 现在您的 pairID 可以存储在向量或其他容器/数组中。只要确保保持索引对齐,以便哈希始终对应于正确的 std::function 对象,然后您可以使用 find ( ) 将迭代器获取到其位置和距离 ( ) 将迭代器转换为需要的索引。

请注意,每次生成容器时都必须执行此操作。由于它基于指针,因此哈希值会随着程序的不同运行而改变。