比较std :: function<> [英] Comparing std::function<>

查看:264
本文介绍了比较std :: function<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to somehow compare two std::tr1::function<> objects? What if I have a collection of function<void(int,float)> objects and want to add and remove event handlers? Adding is trivial, but finding the one to be removed seems to be impossible.

推荐答案

基于Stack Overflow的信息链接,它是可能的,但只有当你将std :: function对象包装在自己的类中。

Based on information from Stack Overflow at the following link, it IS possible but only if you wrap the std::function object in its own class.

std :: vector of std :: function

通过使用包装类,你可以测试两个包装的s​​td :: function指针是否相等,但是不告诉你什么std: :函数包装。所以,改变你的设计可能是一个更好的方法。

By using a wrapper class, you can test whether two wrapped std::function pointers are equal, but that doesn't tell you anything about what the std::function wraps. So, changing your design is probably a better approach.

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

edit: I came back to show the way I've solved a very similar problem.

0)Typedefs的简洁性。

0) Typedefs for conciseness.

    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。

  1. Write your collection of std::function objects by binding pointers to methods or functions. Where you are doing this for static functions, omit some_object_ptr.

some_func some_method ( std::bind ( some_method_ptr, 
                                    some_object_ptr, _1, _2 ) 


  • 使用std :: reinterpret_cast< intptr_t>你的函数的唯一哈希,并使用std ::对这样做的方法。

  • Use std::reinterpret_cast < intptr_t > to create a unique hash for your function, and use it with std::pair to do so for methods.

     method_hash pairID ( reinterpret_cast < intptr_t > ( some_object_ptr ), 
                          reinterpret_cast < intptr_t > ( some_method_ptr ) );
    


  • 现在你的pairID可以存储在一个向量或其他容器/数组中,只要确保索引是对齐的,这样哈希总是对应正确的std :: function对象,然后你可以使用find ()来获取迭代器的位置和距离()以将迭代器转换为所需的索引。

  • Now your pairID can be stored in a vector or other container/array. Just be sure to maintain that the indices are aligned so that a hash always corresponds to the correct std::function object, and you can then use find ( ) to get an iterator to its position and distance ( ) to convert the iterator to the required index.

    这将必须在每次生成您的容器时完成。由于它是基于指针,哈希值会随着程序的不同运行而改变。

    Note that this will have to be done every time your container is generated. Since it's based on pointers, the hashes will change over different runs of your program.

    这篇关于比较std :: function&lt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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