小编wei*_*eng的帖子

将可变参数模板整数转换为 switch 语句

我想做以下事情:

// function that depends on key to do stuff
template <int key>
void bar()  {...}

template <int ...Keys>
void foo(int key) {
   // WHAT SHOULD BE HERE?
}

std::cin >> key;
foo<1,3,5,7,9>(key);
Run Code Online (Sandbox Code Playgroud)

使得它变成

template <int ...Key>
void foo(int key) {
  switch (key) {
      case 1: bar<1>();break;
      case 3: bar<3>();break;
      case 5: bar<5>();break;
      case 7: bar<7>();break;
      case 9: bar<9>();break;
      default: break;
  }
}
Run Code Online (Sandbox Code Playgroud)

如何生成一个 switch 语句,将所有可变参数模板参数枚举为高效的 switch 语句,而无需手动编写 switch 语句?

c++ templates variadic-templates c++17

6
推荐指数
1
解决办法
222
查看次数

标签 统计

c++ ×1

c++17 ×1

templates ×1

variadic-templates ×1