基于运行时参数执行整数模板化函数

Sha*_*ggi 7 c++ metaprogramming switch-statement

我经常有一些基于某种设计方法生成输出的原型行为.我模板化设计方法,它提供了我需要的许多功能.但是,有时设计方法是在运行时给出的,所以我通常需要编写一个巨大的switch语句.它通常看起来像这样:

enum class Operation
{
    A, B
};


template<Operation O>
    void execute();

template<>
    void execute<A>()
    {
        // ...
    }

template<>
    void execute<B>()
    {
        // ...
    }

void execute(Operation o)
{
    switch (o)
    {
    case Operation::A: return execute<Operation::A>();
    case Operation::B: return execute<Operation::B>();
    }
}
Run Code Online (Sandbox Code Playgroud)

我很好奇是否有人为这个系统找到了一个很好的模式 - 这个方法的主要缺点是必须输出所有支持的枚举,并且如果实现了新的枚举,则需要维护几个地方.

e:我应该补充说,弄乱编译时模板的原因是允许编译器在HPC中内联方法以及继承constexpr属性.

e2:实际上,我想我要问的是让编译器使用隐式开关结构生成所有可能的代码路径.也许一些递归模板魔术?

Ale*_*nov 4

如果您确实想使用模板来完成此任务,您可以使用与此类似的技术。

// Here second template argument default to the first enum value
template<Operation o, Operation currentOp = Operation::A>
// We use SFINAE here. If o is not equal to currentOp compiler will ignore this function.
auto execute() -> std::enable_if<o == currentOp, void>::type
{
    execute<currentOp>();
}

// Again, SFINAE technique. Compiler will stop search if the template above has been instantiated and will ignore this one. But in other case this template will be used and it will try to call next handler.
template<Operation o, Operation currentOp = Operation::A>
void execute()
{
    return execute<o, static_cast<Operation>(static_cast<int>(currentOp) + 1)(c);
}
Run Code Online (Sandbox Code Playgroud)