Assume that we have that struct X; and we use C++11 compiler (e.g. gcc 4.7). I’d like to emit some code and attributes if and only if, say, 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
};
- As for the code, I assume that normal
ifsuffices. - But as for the attributes, if one leaves them unused (when
opt = false), will and COULD they be automatically omitted by the compiler? I definitely do not want them there whenopt = false.
The approach to avoid attributes in a class template is to derive from a base class template which is specialized to be empty if the member shouldn’t be there. For example:
With respect to optional code you may get away with a conditional statement but often the code wouldn’t compile. In this case, you’d factor out the code into a suitable function object which be specialized to do nothing when not needed.