Skip to content

Instantly share code, notes, and snippets.

@RomeoV
Created September 19, 2019 12:07
Show Gist options
  • Save RomeoV/28b337c7ff4f5abfcea082079687bbdb to your computer and use it in GitHub Desktop.
Save RomeoV/28b337c7ff4f5abfcea082079687bbdb to your computer and use it in GitHub Desktop.
Showcases c++20 compile-time syntax using constexpr std::transform. Currently compiles with clang 10.0 experimental version.
#include <array>
#include <algorithm>
constexpr int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
template <typename T, std::size_t N, typename F>
constexpr std::array<std::result_of_t<F(T)>, N>
transform(std::array<T, N> array, F f) {
auto array_f = std::array<std::result_of_t<F(T)>, N>{};
std::transform(array.begin(), array.end(), array_f.begin(), [&f](auto el){return f(el);});
return array_f;
}
int main() {
constexpr std::array<int, 4> ints{{1, 2, 3, 4}};
constexpr std::array<int, 4> facts = transform(ints, factorial);
static_assert(facts == std::array<int, 4>{{1, 2, 6, 24}}, "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment