基于运行-时间值取模板

take template basis on run-time value

我有一个 enum:

enum operation {
 plus,
 delete
 //...
}

有一个函数,它有一个 运行-time 参数。

operation_do(plus);

在该函数内部,有一个基于 运行 时间参数的模板函数调用。 重要提示:我不能将 operation_do() 作为模板函数。这是条件。

void operation_do(operation op) {
    call<op>();
}

我有一个编译错误:op 不是常量表达式。

我尝试通过帮助功能解决这个问题,如下所示:

constexpr operation get(operation arg) {
    return arg;
}

void operation_do(operation op) {
    constexpr operation elem = get(op);
    call<elem >();
}

但是还是一样的错误:op不是常量表达式。 有人可以帮忙吗?

And inside that function, there is a template-function call, which is based on a real-time argument. Important: I can NOT make operation_do(), as a template function. This is the condition.

这就是问题所在。

在 C++ 中,run-time 值(因此函数参数,可以是 run-time 值)不能用作模板参数。

出于同样的原因无法通过 constexpr

void operation_do(operation op) {
    constexpr operation elem = get(op); // <--- error
    call<elem >();
}

因为 elem 无法从 run-time 值初始化。

我能想到的最好的方法是使用一系列 if(或者更好的是 switch)从 run-time 值传递到 compile-time值。

有点像

void operation_do (operation op)
 {
   switch ( op )
    { 
      case plus:
         call<plus>();
         break;

      case del:
         case<del>()
         break;
    }
 }

显然,只有在枚举值的数量有限并且可以将 switch 集中在一个地方时,这才可以接受。

请注意,delete 是关键字,因此您不能将其用作标识符。