如何使用任意函数制作函子? [英] How do I make a functor out of an arbitrary function?

查看:51
本文介绍了如何使用任意函数制作函子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆要用作函子的函数(也就是说,使用类型而不是传递指向函数的指针或任何其他类型的数据).

I have a bunch of functions which I want to use as functors (that is, use types instead of pass pointers to the functions, or any other kind of data).

在标准库或标准库+ Boost中是否有一种优雅/惯用/标准的方式来做到这一点?也许以某种方式使用 bind()?

Is there an elegant/idiomatic/standard way of doing this with the standard library, or the standard library + Boost? Perhaps using bind() somehow?

或者我应该使用一些简单化的东西(好吧,有点简单化),例如:

Or should I go with something simplistic (well, kind of simplistic) such as:

template<typename Function, Function& F, typename... Parameters>
struct functor {
    using function_type            = Function;
    using parameters_as_tuple_type = std::tuple<Parameters...>;

    auto operator() (Parameters&&... params) ->
        decltype(F(std::forward<Parameters>(params)...))
    {
        return F(std::forward<Parameters>(params)...);
    }
};

注释:

  • 首选C ++ 11解决方案,但如果您甚至需要C ++ 17,那也很有趣.
  • 我认为,对于重载的函数,我的解决方案"可能不起作用.

推荐答案

首先,是固定类型的具体示例.

First, a concrete example for a fixed type.

int foo( int );
void foo( double );

struct foo_t {
  template<class...Args>
  auto operator()(Args&&...args)const
  ->decltype( foo( std::declval<Args>()... ) )
  {  return ( foo( std::forward<Args>(args)... ) ); }
};

现在 foo_t 是一个对象,可以通过完美转发来调用 foo 的重载.

now foo_t is an object that invokes the overloads of foo via perfect forwarding.

使其具有通用性:

#define RETURNS(...) noexcept(noexcept(__VA_ARGS__)) -> decltype(__VA_ARGS__) { return __VA_ARGS__; }

#define OVERLOAD_SET_TYPE(...) \
  struct { \
    template<class...Args> \
    auto operator()(Args&&...args)const \
    RETURNS( __VA_ARGS__( std::forward<Args>(args)... ) ) \
  }

所以我们可以做

using foo_t = OVERLOAD_SET_TYPE(foo);

实时示例.

您不能将函数的重载集作为对象进行操作;做到这一点的唯一方法是从文字上讲.因此是宏.

You cannot manipulate overload sets of a function as an object; the only way to do it is textually. Hence the macro.

这具有完美转发的所有常见缺陷.无法普遍避免这些缺陷.

This has all of the usual imperfections of perfect forwarding. There is no way to generically avoid those imperfections.

这篇关于如何使用任意函数制作函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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