1

I want to call a lambda and pass the parameters separately.

e.g.:

#include <memory>

template<typename T, typename... TS>
T call(T (*)(TS...) f, TS&&... args) {
    return f(std::forward<TS...>(args...));
}

Thus I want to call this function like this:

call([](auto arg1, auto arg2){
    std::cout << arg1 << ", " << arg2 << std::endl;
}, 1, 2);

This should print out 1, 2.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Arwed Mett
  • 2,614
  • 1
  • 22
  • 35
  • I think [this](https://stackoverflow.com/questions/25392935/wrap-a-function-pointer-in-c-with-variadic-template) is what you're after? – Cory Kramer Dec 31 '20 at 13:27

1 Answers1

3

You can't just slap ... everywhere and hope it works. Understand how parameter packs work and use the correct syntax. Furthermore, the function call() should not return T. Use auto for the return type. And T is already the full type of f, you should not write T (*)(TS...). Here is the fixed version:

template<typename T, typename... TS>
auto call(T f, TS&&... args) {
    return f(std::forward<TS>(args)...);
}
G. Sliepen
  • 7,637
  • 1
  • 15
  • 31