JensB
JensB

Reputation: 939

Is there a way to convert a function pointer to an std::function without specifying return type and argument type?

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?

Upvotes: 1

Views: 604

Answers (2)

P-Gn
P-Gn

Reputation: 24581

If you are using C++17 or above, you could rely on class template argument deduction and simply declare

std::function fn_wrap{&fn};

where fn is the name of your function.

Upvotes: 0

SoronelHaetir
SoronelHaetir

Reputation: 15164

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")

Upvotes: 1

Related Questions