Given a number of functions
f1
,f2
,f3
, ...,fn
I want to create a composite functiong
so thatg(x)
callsf1(f2(f3(...(fn(x))))
.
I came across a blog post which was mentioned in a related Stack Overflow question.
These solutions seem to be very involved. In my own code, I am using a very simple recursion of std::bind
instead.
#pragma once
#include <functional>
// TODO: C++14: remove traits and use auto return type deduction
// traits to infer the return type of recursive binds
template<typename... Fn>
struct composite_function_traits;
// bind a single function with a placeholder
template<typename F1>
struct composite_function_traits<F1> { typedef decltype(std::bind(std::declval<F1>(), std::placeholders::_1)) type; };
template<typename F1>
typename composite_function_traits<F1>::type make_composite_function(F1&& f1)
{
return std::bind(std::forward<F1>(f1), std::placeholders::_1);
}
// recursively bind multiple functions
template<typename F1, typename... Fn>
struct composite_function_traits<F1, Fn...> { typedef decltype(std::bind(std::declval<F1>(), std::declval<typename composite_function_traits<Fn...>::type>())) type; };
template<typename F1, typename... Fn>
typename composite_function_traits<F1, Fn...>::type make_composite_function(F1&& f1, Fn&&... fn)
{
return std::bind(std::forward<F1>(f1), make_composite_function(std::forward<Fn>(fn)...));
}
Are there advantages to the more complex methods for function composition?