Created
September 19, 2019 12:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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