Template metaprogramming

C metaprogramming refers to the technique of meta-programming within the C programming, so a technique to be generated in C code from other program code. Above all templates will be used ( in which case one speaks of Templatemetaprogrammierung ), but also meta-programming using constant expressions, as well as by so-called preprocessor macros.

  • 3.1 Type lists 3.1.1 Processing of type lists
  • 3.1.2 Variadic Templates

Operation

When Templatemetaprogrammierung one makes use of the fact that templates are evaluated at compile time. So you can write code that is evaluated at compile time and only generate the actual code. Here, indeed prolongs the duration of the compilation, because optimized by metaprogramming program paths but it can lead to a shortening of the duration.

The Templatemetaprogrammierung is a programming technique that has been investigated for C intense and fully developed. There are, for example, an implementation of a Lisp derivative or with Spirit a realized with the help of C templates parser.

Krzysztof Czarnecki and Ulrich W. Ecker iron are considered the pioneers of this technique. Outstanding work on the C metaprogramming by Andrei Alexandrescu come, he particularly with his book Modern C Design - Generic Programming and applied design pattern made ​​known.

The Templatemetaprogrammierung in C is Turing-complete, which means that each algorithm can be implemented by means of template metaprogramming. At the same time, it follows that there can be no proper C compiler that every C program is compiled, or is no longer in general decidable whether a C program is correct.

In the Templatemetaprogrammierung there is no mutable variables, ie once a certain value -initialized elements retain their value forever. Interestingly, one consequence of the fact that C template meta programs generally - unlike C run- time programs - represent a form of purely functional programming. The control flow is done in Templatemetaprogrammen therefore using recursion.

Examples

Power calculation using templates

The following example calculates the power for positive exponents:

Template struct { potency    enum { value = B * potency :: value }; };   template struct potency {    enum { value = 1}; };   const int P = potency < 10, 3 > :: value; Explanation: The template potency instantiated itself recursively, where the exponent is reduced with each recursion by 1. The template has a so-called specialized in the event that the exponent is 0, and delivers the result back in the case 1, it assumes the role of specialized termination condition of the recursion.

So can the structure of the code as pseudo code

P (B, S): P = B * (B, E-1) P (B, 0 ) = 1 describe.

Power calculation using constant expressions

The following example also calculates the power, in this case with the help of constant generalized terms:

Constexpr int potency (int base, unsigned int exp) {    return ( exp == 0)? 1: basic * potency ( base, exp -1); } const int P = potency (10, 3); Explanation: Views of simple functions can be performed at compile-time and used in constant expressions. The function to be called for must be provided with constexpr. ( This is a new feature of C 11, the recent revision of the international standard ISO C from the year 2011.)

Constructs used

Class templates take in the C Templatemetaprogrammierung the role of functions at runtime. You can types and constant values ​​, including references to functions that accept as a parameter and by means of a typedef a type or store by means of a enum or constant has a value, which thus plays the role as a return type. Specializations of templates correspond to branches and thus allow the program flow control.

Based on this, complex functions and data structures to implement that are evaluated at compile time. Such can be used to generate about class structures, and thus to simplify the example implementation of certain design pattern, or to synthesize functions.

Libraries like Boost or Loki implement certain basic constructs that facilitate such metaprogramming, about if or fold - like constructs at compile time, or about data structures.

Type lists

So-called type lists provide a simple example of using templates defined at compile-time data structure represents a typical implementation looks like this:

Struct NullType; template struct Type List {    typedef H Head;    typedef T Tail; }; typedef type List < Type1, Type List < type2, type List < Type3, NullType >>> MyList; Type lists can be processed by means of templates, but for the end must be characterized by a ' null type '.

It is very expensive to develop a functionality based on type lists. With appropriate basic functions, however, is an elegant use possible. The problem in the use of results from the fact that the possibilities for metaprogramming were discovered subsequently and for them no specially designed language constructs exist.

Processing of type lists

In C there is no easy way to access the elements of type lists. If a type list to be processed, each iteration must be in a separate function call (with tail as template parameter ) or via the instantiation of a class template for each iteration. Typically, the processing is terminated by a specialization for the null type.

Variadic templates

In C 11 variadic templates, what templates with any number of parameters, catchment have held. Such functionality can indeed already be realized with type lists, such as in Loki and Boost, but the variadic in the programming language built-in support template offers the advantage of a much shorter build times, since the processing of lists of types is associated with very high costs. Instead of the parameter is chosen in this case a single tuple parameter. The execution must take place over recursive instantiation, so structurally strong similarity exists with variadic templates.

Tuple

An elementary example of generation of data structures by means of metaprogramming make tuple dar. This can be realized with variadic templates ( formerly type lists or ). To this end, one usually applies a class template that takes as many types as parameters and for each type contains a field of this type. In C this must be done in a recursive way again. For example, a tuple of a tuple with one element inherit less. Subsequently, such operations can implement index accesses that must take place during the translation, or synthesize operations such comparisons and hashes that can be applied to the tuples at runtime.

Pros and cons of Templatemetaprogrammierung

  • Trade-off between compile time and run time: is Since the entire template source processed, analyzed and used during translation, the translation lasts longer, while the executable code can thereby gain in efficiency. Although this additional effort in general is very small, it can on large projects or projects in which templates are used intensively, have great influence on the duration of the translation.
  • Generic programming: Templatemetaprogrammierung allows a higher abstraction. Therefore Templatemetaprogrammierung can lead to shorter code and increased maintainability.
  • Readability: Compared with conventional C programming syntax and spelling of the Templatemetaprogrammierung seem unusual at first. Advanced or even the most non-trivial Templatemetaprogrammierung may therefore be difficult to understand. This can Metaprograms of programmers who are inexperienced in Templatemetaprogrammierung be difficult to maintain, especially not correspond to the purely functional structure of the usual structure of C . However, the latter depends also on how the Templatemetaprogrammierung was implemented in the specific case.
  • Poor support by development tools: In the existing development tools, it is not possible to follow the gradual Metagenerierung. Due to lack of language resources, it is far too difficult to generate meaningful error messages for metaprogramming. Most compilers give out error messages, from which it is difficult to infer the actual error.

Pictures of Template metaprogramming

157590
de