如何在 c++ 中传递 std-functor并在不知道具体是哪一个的情况下使用它
我这里有类似排序算法的东西,我想向它传递一个函子,它提供排序标准(std::binary_function)。因此,如果给出了 std::less ,它应该调用 T.operator<() 。
问题是,成员函数operator()不是虚拟的。所以我需要知道给出了哪种类型的对象,以执行动态转换,这并不是很好。
问候,
丹尼斯
I have something like a sort-algorithm here, and I want to pass it a functor, which provides the sorting criteria (std::binary_function). So it should call T.operator<() for example if std::less is given.
Problem is, the member function operator() is not virtual. So I need to know which type of object was given, to perform a dynamic cast which is not really nice.
Regards,
Dennis
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么要进行动态演员表?通常你不需要那个。只需调用函子的
operator()
就像调用普通函数一样。函子的全部要点是它们的行为类似于普通函数,并且您将模板参数传递到算法中(不是吗?)来处理不同的函子(和函数)类型。
当然,这整个事情的前提是您实际上将模板参数传递到函数中。
std::binary_function
不适合作为虚拟基类。它的存在只是为了定义一些方便的 typedef。因此,您的函数声明应如下所示:Why do you want to perform a dynamic cast? Normally you don’t need that. Just call the functor’s
operator()
just like you would call a normal function.The whole point of a functor is that they behave like normal functions and you’re passing a template parameter into your algorithm (aren’t you?) to handle different functor (and function) types.
Of course, this whole thing is predicated on the fact that you are actually passing a template parameter into your function.
std::binary_function
is not suited as a virtual base class. It merely exists to define a few handy typedefs. Thus, your function declaration should look like this:不能将函子作为模板参数传递,以实现静态多态性吗?
Can't you pass your functor as a template parameter, so to have static polymorphism?
您可以使用 Qt Signal 和 Slots,也可以使用 Boost.Function
You can use Qt Signal and Slots or you can use Boost.Function