Home > Enterprise >  How to make a function that accepts another one with argument tuple
How to make a function that accepts another one with argument tuple

Time:10-06

I need a function My_func that works like this

auto f = [](const std::tuple<string, double>& t) { return std::get<0>(t); };
    assert(My_func(f)("Hello", 8.5) == f({"Hello", 8.5}));

Now i have

template <class F>
constexpr auto My_func(F&& f) {
    return [f](auto&& args...) { return std::forward<F>(f)(args); };
}

But it doesn't work.What should i fix?

CodePudding user response:

First of all you need My_func to be syntactically valid. You have a pack args that is not expanded in the lambda. Then you need to mention tuple somewhere. C is not psychic.

Luckily, there exists std::forward_as_tuple that does exactly what you need here

template <class F>
constexpr auto My_func(F&& f) {
    return [f = std::forward<F>(f)](auto&& args...) { return f(std::forward_as_tuple(args...)); };
}

CodePudding user response:

template <class F>
constexpr auto My_func(F&& f) 
{
   return [f = std::forward<F>(f)](auto&&... args) { 
        return f(std::make_tuple(std::forward<decltype(args)>(args)...)); 
   };
}
  • Related