假设我们有这个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
};
Run Code Online (Sandbox Code Playgroud)
if
就足够了.opt = false
),将和COULD他们可以由编译器自动忽略?我绝对不希望他们在那里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> {
...
};
Run Code Online (Sandbox Code Playgroud)
对于可选代码,您可能会使用条件语句,但通常代码无法编译。在这种情况下,您可以将代码分解为合适的函数对象,该对象专门用于在不需要时不执行任何操作。
归档时间: |
|
查看次数: |
183 次 |
最近记录: |