Template function for applying args to function

Viewed 72

I trying to write a function (call it apply_args()) that takes a specific function or function object and arguments for calling this object, and calls it using the perfect forwarding.

Example:

auto fun = [](std::string a, std::string const& b) { return a += b; };

std::string s("world!");

// s is passing by lvalue ref,
// temporary object by rvalue ref 
s = apply_args(fun, std::string("Hello, "), s);

How can I implement that function?

2 Answers
template <typename Func, typename ...Args>
decltype(auto) apply_args(Func &&f, Args &&...args) {
    return f(std::forward<Args>(args)...);
}

If you accept to pass the fun lambda as +fun (transforming it in a function pointer), I suppose you can simply write apply_args() as

template <typename R, typename ... Fts, typename ... As>
R apply_args (R(*fn)(Fts...), As && ... as)
 { return fn(std::forward<As>(as)...); }

The full example

#include <string>
#include <iostream>
#include <functional>

template <typename R, typename ... Fts, typename ... As>
R apply_args (R(*fn)(Fts...), As && ... as)
 { return fn(std::forward<As>(as)...); }

int main ()
 {
   auto fun = [](std::string a, std::string const& b) { return a += b; };

   std::string s("world!");

   s = apply_args(+fun, std::string("Hello, "), s);

   std::cout << s << std::endl;
 }
Related