Home > OS >  Is there a way to convert a function pointer to an std::function without specifying return type and
Is there a way to convert a function pointer to an std::function without specifying return type and

Time:12-10

I have a function pointer that I need to pass to a function that expects a std::function. The function that takes the std::function is templated and uses the std::function's arguments to deduce a parameter pack, meaning an implicit conversion won't work.

I could construct the std::function myself, but the function being passed has many arguments, and writing them into the template brackets of std::function will not be sustainable, as I need to do this often with many similar functions that I pass to this function.

Is there a way to convert a function pointer to a std::function without specifying the return type and arguments, by some form of deducing?

This is what I've tried so far:

template <auto* F>
struct stdfunc {};

template <class Ret, class... Args, auto (*F)(Args...) -> Ret>
struct stdfunc<F>
{
    typedef std::function<Ret(Args...)> type;
};

The above code does not work as intended. I found the syntax in this answer. In that case, it wasn't used for this purpose, but surely there is a way to achieve what I'm trying to do using this technique? It seems like all the pieces are there, I just have to put them in the right place.

Am I on the right track?

CodePudding user response:

I suggest:

template<typename Func>
auto make_function(Func ptr)
{
    return std::function<std::remove_pointer_t<Func>>(ptr);
}

and then simply pass "make_function(my_func)".

(Thanks toRemy Lebeau for suggesting use of "auto")

CodePudding user response:

Do you mean this one?

#include <functional>

template<class F>
struct stdfunc {};

template <class Ret, class... Args>
struct stdfunc<Ret(*)(Args...)> {
  typedef std::function<Ret(Args...)> type;
};

Demo.

  • Related