简体   繁体   English

根据运行时值取模板

[英]take template basis on run-time value

I have an enum :我有一个enum

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

There is function, which has a run-time argument.有一个函数,它有一个运行时参数。

operation_do(plus);

And inside that function, there is a template-function call, which is based on a run-time argument.在该函数内部,有一个基于运行时参数的模板函数调用。 Important: I can NOT make operation_do() , as a template function.重要提示:我不能将operation_do()作为模板函数。 This is the condition.这是条件。

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

I have a compiled error: op is not a constant expression.我有一个编译错误: op不是常量表达式。

I tried to resolve this with the help function, like this:我尝试使用帮助功能解决此问题,如下所示:

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

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

But it is still the same error: op is not a constant expression.但它仍然是同样的错误: op不是一个常量表达式。 Can anyone help, please, with this?任何人都可以帮忙吗?

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.重要提示:我不能将 operation_do() 作为模板函数。 This is the condition.这是条件。

This is the problem.这就是问题。

In C++ a run-time value (so a function argument, that can be a run-time value) can't be used as template parameter.在 C++ 中,运行时值(因此函数参数,可以是运行时值)不能用作模板参数。

For the same reason can't works the passage through a constexpr value出于同样的原因不能通过constexpr

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

because elem can't be initialized from a run-time value.因为elem不能从运行时值初始化。

The best I can imagine is the use of a sequence of if (or, maybe better, a switch ) to pass from a run-time value to a compile-time value.我能想象到的最好的方法是使用一系列if (或者,也许更好, switch )从运行时值传递到编译时值。

Something as某事如

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

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

Obviously this is acceptable only if the number of the enum value is limited and if you can concentrate the switch in a single place.显然,只有在枚举值的数量有限并且您可以将switch集中在一个地方时,这才是可以接受的。

Note that delete is a keyword, so you can't use it as an identifier.请注意, delete是一个关键字,因此您不能将其用作标识符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM