我经常有一些基于某种设计方法生成输出的原型行为.我模板化设计方法,它提供了我需要的许多功能.但是,有时候设计方法是在运行时给出的,所以我通常需要编写一个巨大的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:实际上,我想我要问的是让编译器使用隐式开关结构生成所有可能的代码路径.也许一些递归模板魔术?
解决方法
如果您真的想要使用模板执行此任务,您可以使用类似于
this one的技术.
// 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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。