Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active August 29, 2015 14:07
Show Gist options
  • Save dgodfrey206/ac0fc92f428a7adb01bd to your computer and use it in GitHub Desktop.
Save dgodfrey206/ac0fc92f428a7adb01bd to your computer and use it in GitHub Desktop.
Allows a functional style syntax for composing functions
#include <functional>
template<class T>
struct wrap_impl
{
wrap_impl(T&& x) : data(std::forward<T>(x)) { }
T get() const & { return data; }
T&& get() && { return std::move(data); }
private:
T data;
};
template<class R, class... Args>
struct wrap_impl<R (&)(Args...)> : wrap_impl<std::function<R (Args...)>>
{
using wrap_impl<std::function<R (Args...)>>::wrap_impl;
using wrap_impl<std::function<R (Args...)>>::get;
};
template<class T>
wrap_impl<T> wrap(T&& x)
{
return wrap_impl<T>(std::forward<T>(x));
}
template<typename T, typename U>
auto operator|(wrap_impl<std::function<T>>&& lhs,
wrap_impl<std::function<U>>&& rhs)
{
return [lhs = std::move(lhs),
rhs = std::move(rhs)] (auto&&... x) { return lhs.get()(rhs.get()(std::forward<decltype(x)>(x)...)); };
}
int main()
{
auto f = [] (int x) { return x*10; };
auto g = [] (int y) { return y*10; };
(wrap(f) | wrap(g))(5); // f(g(5))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment