Skip to content

Instantly share code, notes, and snippets.

@nbenn
Last active August 5, 2019 15:16
Show Gist options
  • Save nbenn/bae85857e9be915e4784e53c37f04605 to your computer and use it in GitHub Desktop.
Save nbenn/bae85857e9be915e4784e53c37f04605 to your computer and use it in GitHub Desktop.
Runtime index for choosing type
#include <stdexcept>
#include <tuple>
#include <iostream>
// terminating case to avoid if-constexpr
template <template<class> class F, typename R, typename... Ar>
R dispatch_impl(int, Ar&&... rgs) {
throw std::runtime_error("error");
}
// main recursive case
template <template<class> class F, typename R, typename... Ar,
typename Ty, typename... pes>
R dispatch_impl(int index, Ar&&... rgs) {
if (index == 0) {
return F<Ty>::f(std::forward<Ar>(rgs)...);
} else {
return dispatch_impl<F, R, Ar..., pes...>(index - 1,
std::forward<Ar>(rgs)...);
}
}
template <template<class> class F, typename... Ar>
auto dispatch_type(int index, Ar&&... rgs) {
return dispatch_impl<F, int, Ar..., int, char>(index,
std::forward<Ar>(rgs)...);
}
template <typename T> struct foo;
template <> struct foo<int> { static int f(int i) {return 1;} };
template <> struct foo<char> { static int f(int i) {return 2;} };
int main(void) {
std::cout << "int: " << dispatch_type<foo>(1, 1) << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment