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
};
if
suffices.opt = false
), will and COULD they be automatically omitted by the compiler? I definitely do not want them there when opt = false
." typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.
In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With