Search code examples
c++templatestemplate-meta-programming

Use int-templated function with non-constexpr values


I have some function

template<int N>
auto foo();

I want to call this function with template parameters that are unknown at compile time, but they can only be numbers 1 to c (where c is a fixed constant, e.g. 10). Is there a better general solution to this problem than the following?

auto foo(int n)
{
  switch(n) {
    case 1:
      return foo<1>();
    case 2:
      return foo<2>();
...
    case 10:
      return foo<10>();
  }
}

This solution is getting quite verbose if the function shall be used for a larger set of integers.

This template parameter is necessary because the function uses a class with such a template argument where this is used for the size of a static-sized array. But this should not be really relevant for the problem. I cannot change the templated version.


Solution

  • Sure:

    template <int... Ns>
    decltype(auto) dispatch_foo(int const n, std::integer_sequence<int, Ns...>) {
        static constexpr void (*_foos[])() { &foo<Ns>... };
        return _foos[n]();
    }
    
    template <int Nmax>
    decltype(auto) dispatch_foo(int const n) {
        return dispatch_foo(n, std::make_integer_sequence<int, Nmax>{});
    }
    

    Usage:

    dispatch_foo<c>(n);
    

    See it live on Wandbox