When is a value pre-computed using TMP ever really useful?

Scott Meyers in Effective C ++ points to the ability to do this, for example, matrix operations in the compiler, as a reason for implementing some of your algorithms in template classes / functions. But these functions cannot work with arguments that are defined at runtime, obviously - they only work for numbers that are written to the program or, at best, specified as arguments to the compiler. Once the program is compiled, it will use the same output value each time it starts. In this case, why not just calculate this value using a regular (non-template) program and simply write it to the original program, if necessary? This does not speed up the calculation, for example. 1000-pt. fft in the compiler than with a regular program.

The best I can come up with is if you need to compile different versions of your program for different clients, then TMP can save you some time. But does it really arise?

+4
source share
1 answer

The main advantage of TMP when it comes to operations with matrices is the inability to recompute the result of operations with the matrix, but rather the ability to optimize the generated code to perform the actual calculation of the matrix at runtime. You are right - it would be unlikely that you would ever want to pre-comprehend the matrix in the program, but salmon wants to optimize the mathematical math during compilation before the program starts to work. For example, consider this code:

Matrix a, b, c; /* ... Initialize these matrices ... */ Matrix d = a + b + c; 

This last line uses some overloaded operators to evaluate the matrix expression. Using traditional C ++ programming methods, this will work as follows:

  • Compute b * c, returning a temporary matrix object containing a copy.
  • Calculate a + b + c by returning the temporary copy again.
  • Copy the result to d.

This is slow - there is no reason to make any copies of any values ​​here. instead, we should just loop around all the indices in the matrices and summarize all the values ​​we found. However, using the TMP method called expression patterns , you can implement these operators in such a way that in fact this calculation is an intelligent, optimized way than a slow, standard way. This is a family of techniques that I think Meyers mentioned in the book.

The best-known examples of TMP are simple programs for precompiling values ​​at compile time, but in practice they are much more complex methods like these that are actually used in practice.

+6
source

Source: https://habr.com/ru/post/1338644/


All Articles