如何在 c++ 中传递 std-functor并在不知道具体是哪一个的情况下使用它

发布于 2024-10-10 10:57:51 字数 196 浏览 0 评论 0原文

我这里有类似排序算法的东西,我想向它传递一个函子,它提供排序标准(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月野兔 2024-10-17 10:57:51

问题是,成员函数operator()不是虚函数。所以我需要知道给定的是哪种类型的对象,以执行动态转换,这并不是很好。

为什么要进行动态演员表?通常你不需要那个。只需调用函子的 operator() 就像调用普通函数一样。

函子的全部要点是它们的行为类似于普通函数,并且您将模板参数传递到算法中(不是吗?)来处理不同的函子(和函数)类型。

当然,这整个事情的前提是您实际上将模板参数传递到函数中。 std::binary_function适合作为虚拟基类。它的存在只是为了定义一些方便的 typedef。因此,您的函数声明应如下所示:

template <typename TBinaryFunction>
void your_algorithm(rest of parameters …, TBinaryFunction f);

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.

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:

template <typename TBinaryFunction>
void your_algorithm(rest of parameters …, TBinaryFunction f);
甲如呢乙后呢 2024-10-17 10:57:51

不能将函子作为模板参数传递,以实现静态多态性吗?

Can't you pass your functor as a template parameter, so to have static polymorphism?

提笔落墨 2024-10-17 10:57:51

您可以使用 Qt Signal 和 Slots,也可以使用 Boost.Function

You can use Qt Signal and Slots or you can use Boost.Function

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文