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



我经常有一些基于某些设计方法生成输出的原型行为。我模板化了设计方法,它实现了我需要的许多功能。然而,有时设计方法是在运行时给出的,所以我通常需要编写一个庞大的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>();
    }
}

我很好奇是否有人为这个系统想出了一个很好的模式——这种方法的主要缺点是必须输入所有支持的枚举,并且如果实现了新的枚举,则必须在几个地方进行维护。

e:我应该补充一下,使用编译时模板的原因是允许编译器在HPC中内联方法以及继承constexpr属性。

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

如果你真的想在这个任务中使用模板,你可以使用类似的技术。

// 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);
}
template<class F, std::size_t...Is>
void magic_switch( std::size_t N, F&& f, std::index_sequence<Is...> ){
  auto* pf = std::addressof(f);
  using pF=decltype(pf);
  using table_ptr = void(*)(pF);
  static const table_ptr table[]={
    [](pF){ std::forward<F>(*pf)( std::integral_constant<std::size_t, Is>{} ); }...
  };
  return table[N]( pf );
}
template<std::size_t Count, class F>
void magic_switch( std::size_t N, F&& f ){
  return magic_switch( N, std::forward<F>(f), std::make_index_sequence<Count>{} );
}

这将创建一个跳转表,该跳转表调用编译时常量上的lambda,并根据运行时常量选择哪个条目。这与switch case语句有时被编译为

非常相似。
void execute(Operation o) {
  magic_switch<2>( std::size_t(o), [](auto I){
    execute<Operation(I)>();
  } );
}

可以将其修改为返回non-void,但所有分支必须返回相同的类型。

最新更新