Last active
November 25, 2019 02:08
-
-
Save talybin/03a925499c5cb7dbe4bb5caf71c2584c to your computer and use it in GitHub Desktop.
Get index by run-time value.
This file contains hidden or 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 <iostream> | |
| #include <utility> | |
| template <size_t I, class F> | |
| inline auto ct_value(F&& f) | |
| { | |
| return std::forward<F>(f)(std::integral_constant<size_t, I>()); | |
| } | |
| template <class F, size_t... I> | |
| inline auto ct_value(size_t v, F&& f, std::index_sequence<I...>) | |
| { | |
| using R = std::invoke_result_t<F, std::integral_constant<size_t, 0>>; | |
| static constexpr R (*vtable[])(F&&) = { &ct_value<I>... }; | |
| if (v >= sizeof...(I)) | |
| return R(); | |
| else | |
| return vtable[v](std::forward<F>(f)); | |
| } | |
| template <size_t N, class F> | |
| inline auto ct_value(size_t v, F&& f) | |
| { | |
| return ct_value(v, std::forward<F>(f), std::make_index_sequence<N>()); | |
| } | |
| int main() | |
| { | |
| int x; | |
| std::cin >> x; | |
| ct_value<1024>(x, [](auto I) { | |
| std::cout << "found: " << I << '\n'; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment