Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional code in a template class

Tags:

c++

gcc

c++11

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
};
  1. As for the code, I assume that normal if suffices.
  2. 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.
like image 533
Cartesius00 Avatar asked Dec 09 '12 18:12

Cartesius00


People also ask

What is Typename in C++ template?

" 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.

What is a template template parameter in C++?

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.

What is templated code?

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.

What is a non-type template parameter?

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.


1 Answers

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.

like image 138
Dietmar Kühl Avatar answered Sep 29 '22 09:09

Dietmar Kühl