Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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,
template <template<class> class F, typename... Ar>
auto dispatch_type(int index, Ar&&... rgs) {
return dispatch_impl<F, int, Ar..., int, char>(index,
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
You can’t perform that action at this time.