c – 模板类中的可选代码
发布时间:2020-12-16 05:02:46 所属栏目:百科 来源:网络整理
导读:假设我们有结构X;我们使用C 11编译器(例如 gcc 4.7).我想发出一些代码和属性,当且仅当,例如,opt = true. template bool optstruct X { void foo() { EMIT_CODE_IF(opt) { // optional code } // ...common code... } int optional_variable; // Emitted if a
假设我们有结构X;我们使用C 11编译器(例如
gcc 4.7).我想发出一些代码和属性,当且仅当,例如,opt = true.
template <bool opt> struct X { void foo() { EMIT_CODE_IF(opt) { // optional code } // ...common code... } int optional_variable; // Emitted if and only if opt is true }; >至于代码,我认为正常就足够了. 解决方法
避免类模板中的属性的方法是从基类模板派生,如果成员不在那里,该模板专门为空.例如:
template <bool Present,typename T> struct attribute { attribute(T const& init): attribute_(init) {} T attribute_; }; template <typename T> struct attribute<false,T> { }; template <bool opt> class X: attribute<opt,int> { ... }; 关于可选代码,您可以使用条件语句,但通常代码不会编译.在这种情况下,您需要将代码分解为合适的函数对象,该对象专门在不需要时不执行任何操作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |