mercredi 19 avril 2017

How do I make a functor out of an arbitrary function?

I have a bunch of functions which I want to use as functors (that is, use types instead of pass pointers to the functions - which I would really rather not do).

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) 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(params...))
    {
        return F(params...);
    }
};

Note: C++11 solutions preferred, but if you have something requiring even C++17, that's also interesting.

Aucun commentaire:

Enregistrer un commentaire