繁体   English   中英

模板类中的可选代码

[英]Optional code in a template class

假设我们有struct 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
};
  1. 至于代码,我认为正常, if足够。
  2. 至于属性,如果一个人留给他们未使用(当opt = false ),将和能将它们由编译器自动忽略? opt = false时,我绝对不希望他们在那里。

避免类模板中的属性的方法是从基类模板派生,如果成员不在那里,该模板专门为空。 例如:

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> {
    ...
};

关于可选代码,您可以使用条件语句,但通常代码不会编译。 在这种情况下,您需要将代码分解为合适的函数对象,该对象专门在不需要时不执行任何操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM