Skip to content

Instantly share code, notes, and snippets.

@revsic
Last active October 26, 2018 12:15
Show Gist options
  • Save revsic/8b7659ae39e2ee21d10779b261db7d82 to your computer and use it in GitHub Desktop.
Save revsic/8b7659ae39e2ee21d10779b261db7d82 to your computer and use it in GitHub Desktop.
cpp implementation of constexpr fold
#include <iostream>
template <typename F>
struct Fold {
F func;
template <typename Fs>
constexpr Fold(Fs&& func) : func(std::forward<Fs>(func)) {}
template <typename T, typename U>
constexpr auto impl(T&& arg1, U&& arg2) {
return func(std::forward<T>(arg1), std::forward<U>(arg2));
}
template <typename T, typename... Ts>
constexpr auto impl(T&& init, Ts&&... rest) {
return func(std::forward<T>(init), impl(std::forward<Ts>(rest)...));
}
template <typename... Ts>
constexpr auto operator()(Ts&&... args) {
return impl(std::forward<Ts>(args)...);
}
};
template <typename F>
constexpr auto fold(F&& func) {
return Fold<F>(std::forward<F>(func));
}
int main() {
auto max = [](auto a, auto b) constexpr { return a > b ? a : b; };
constexpr int result = fold(max)(1, 4, 3, 5, 2);
std::cout << result << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment