I’m trying to write a function that receives a callable object as a parameter and returns a modified version of that callable object.
Here is an example of what I’m trying to create:
template<class R, class... Args>
std::function<R(Args...)> ModifyFunction(std::function<R(Args...)> f)
{
return [f](Args... args) {
// Take some extra actions here...
return f(std::forward<Args>(args)...);
};
}
It works fine if I pass a std::function
object to it:
std::function<void()> f([] {
std::cout << "Test" << std::endl;
});
auto modified = ModifyFunction(f);
modified();
But it fails to compile if I pass a different callable type, for example, a lambda:
auto modified = ModifyFunction([] {});
modified();
Is it possible to write a function that will work on any callable type?
Preferably with C++11.
10
You might get rid of std::function
and do
in C++14, we just use auto
as return type:
template <typename F>
auto ModifyFunction(F f)
{
return [f](auto... args) -> decltype(f(std::forward<decltype(args)>(args)...)){
// Take some extra actions here...
return f(std::forward<decltype(args)>(args)...);
};
}
In C++11, you might create a named class instead of the lambda
template <typename F>
class Wrapper
{
F f;
public:
explicit Wrapper(F f) : f(std::move(f)) {}
template <typename...Args>
auto operator()(Args&&... args) -> decltype(f(std::forward<Args>(args)...))
{
// Take some extra actions here...
return f(std::forward<Args>(args)...);
}
};
template <typename F>
Wrapper<F> ModifyFunction(F f)
{
return Wrapper<F>(f);
}
0