Metaprogramming

Metaprogramming in C++ (a.k.a template metaprogramming) uses the fact that templates are instantiated at compile time an not at run time. This makes it possible to create a template which calculates a value at return time, a value which can then be used as a constant in the rest of the program.

Say that we create a template struct which only contains a single value

the definition of the value is recursive and refers to the calculation of the factorial of a value one-less than the requested value. However, this will not in itself compile since the compiler will get stuck in an infinite loop trying to calculate the factorial of one-less than the value eventually crashing the compilation. To stop the compiler it must be given a stopping condition, a special case where we explicitly tell the compiler what the value of the factorial is. This is done like this:

And to calculate the value of the factorial, you simply need to create an instance of the template:

 

See also the C++ book: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming

Facebookgoogle_pluslinkedinmail

The const keyword

The const keyword is used to show both other developers and the compiler that an object is constant and its contents cannot be changed. If you anyway try to change the contents of a const object will generate an error already at compile time. It is a good practice to add the const keyword to a parameter, a members or a method to show that the value is not going to be changed. This can both make the intent of the code more clear to the user, and can make the code faster since the compiler can make certain optimizations knowing that the object is not going to change its value.

The difference between the const keyword and the constexpr keyword is that the value of a constexpr constant must be resolved at compile time whereas the value of a const constant can be resolved at run time (or at compile time).

The const keyword can be used in the following contexts:

Const class

An object can be made constant at creation by declaring the object as const:

Any attempt to change the contents of the object christmasDay will result in a compiler error:

 

Const member functions

Adding the const keyword to a member function (added at the end of the function declaration, after the parameters) states that this method will not change the state of the object.

The const keyword after the declaration of the method getYear() shows that calling this method will not change any members of the object. This also means that we are allowed to call this method even if the object is const.

 

Const parameters

Parameters to functions can also be declared as const. There are two positions where the const keyword can be added.

 

 

 

Facebookgoogle_pluslinkedinmail