0

I want to transform all functions, which take tuples as arguments, passed to Foo into functions which take plain arguments.

auto f = [](const std::tuple<int, char>& t) { return std::get<0>(t); };

template <typename F>
auto Foo(F&& f) {
    ...
}

Foo(f)(42, 'a')

My idea was to do something like this

template <typename ReturnType, typename... Args>
auto Foo(std::function<ReturnType(const std::tuple<Args...>&)> f) {
    return [&](Args&&... args) -> ReturnType {
      return f({std::forward<Args>(args)...});  
    };
}

But compiler couldn't infer template arguments for a lambda and ignored this candidate.

Joseph Kirtman
  • 349
  • 2
  • 10
  • I think you need to use std::apply, std::apply([](auto &&... args) { my_func(args...); }, my_tuple); (also see https://stackoverflow.com/questions/687490/how-do-i-expand-a-tuple-into-variadic-template-functions-arguments) – Pepijn Kramer Sep 19 '21 at 09:16

1 Answers1

3

If you don't really need the parameter types. simply

template <typename Callable>
auto Foo(Callable f) {
    return [=](auto&&... args)->decltype(auto){
      return f({std::forward<decltype(args)>(args)...});
    };
}

the plus side is Foo can now accept more generic f, which could have multiple opreator() defined.

apple apple
  • 10,292
  • 2
  • 16
  • 36