c – 使用模板来避免类似的功能
发布时间:2020-12-16 10:08:12 所属栏目:百科 来源:网络整理
导读:假设我有2个函数对参数执行完全相同的操作,但使用不同的常量集来执行此操作.对于一个过于简单的例子: int foo1(int x){ return 3+4*x}int foo2(int x){ return 6-4*x} 在实际应用程序中假设会有多个参数和常量/文字,当然计算会复杂得多. 为了简单起见以及可
假设我有2个函数对参数执行完全相同的操作,但使用不同的常量集来执行此操作.对于一个过于简单的例子:
int foo1(int x){ return 3+4*x } int foo2(int x){ return 6-4*x } 在实际应用程序中假设会有多个参数和常量/文字,当然计算会复杂得多. int foo(int x,int funcType){ const int firstConst = (funcType==1) ? 3 : 6; const int secondConst = (funcType==1) ? 4 : -4; return firstConst+secondConst*x; } 但是因为我总是在编译时知道我想要使用哪个函数,所以我想使用模板来避免分支.有没有办法做到这一点? 解决方法templatr<int funcType> void foo(int x){ const int firstConst = (funcType==1) ? 3 : 6; const int secondConst = (funcType==1) ? 4 : -4; return firstConst+secondConst*x; } 在任何非零优化设置下都没有值得使用的编译器将具有上述模板函数的运行时分支. 它比特质课更容易阅读. 一般来说,你可以通过这种技术获得乐趣,编写可以编译为紧凑操作的长分支代码.如果你的代码很好地分解成碎片(比如bool do_foo作为模板参数),这可以很好地扩展. 除此之外,您可能希望避免维护数字ID的中央列表.通过标签调度到constexpr ADL启用特征函数来查找特征,或者将一个模板非类型指针指向constexpr结构,两者都可以通过分布式函数子类型声明给出零开销效果. 最后,你可以直接传递一个traits类: template<class Traits> void foo(int x){ return x*Traits::z+Traits::y; } 要么 template<class Traits> void foo(int x){ return x*Traits{}.z+Traits{}.y; } 甚至 template<class Traits> void foo(int x,Traits traits={}){ return x*traits.z+traits.y; } 根据具体需要. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |