Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 613
Henk Avatar asked Feb 26 '26 07:02

Henk


1 Answers

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

like image 124
Quentin Avatar answered Feb 27 '26 20:02

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!