使用具有非 constexpr 值的 int 模板函数

Hen*_*enk 2 c++ templates template-meta-programming

我有一些功能

template<int N>
auto foo();
Run Code Online (Sandbox Code Playgroud)

我想使用编译时未知的模板参数调用此函数,但它们只能是数字 1 到c(其中c是固定常量,例如 10)。这个问题有没有比以下更好的通用解决方案?

auto foo(int n)
{
  switch(n) {
    case 1:
      return foo<1>();
    case 2:
      return foo<2>();
...
    case 10:
      return foo<10>();
  }
}
Run Code Online (Sandbox Code Playgroud)

如果该函数应用于更大的整数集,则此解决方案会变得非常冗长。

此模板参数是必需的,因为该函数使用具有此类模板参数的类,其中 this 用于静态大小数组的大小。但这不应该与问题真正相关。我无法更改模板化版本。

Que*_*tin 6

当然:

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>{});
}
Run Code Online (Sandbox Code Playgroud)

用法:

dispatch_foo<c>(n);
Run Code Online (Sandbox Code Playgroud)

在 Wandbox 上实时观看