Optional code in a template class

c++, c++11, gcc

Solution

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:

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

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.

Problem

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 `if` suffices. - 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 when `opt = false`.

Original source