Why is metaprogramming important? Isn't it easier to generate a code script?

Recently, I used C ++ all over the world when metaprogramming became popular, and I'm coming back now. In the past, I did a bunch of writing C ++ code. Although I see that metaprogramming is powerful, does it really offer anything compared to creating a code script? One of the advantages that I see is not a "trip around the world", where metaprogramming is built into the source code, so there is always synchronization between the non-execution code and the run-time code.

+3
source share
4 answers

You already have a few answers that mention type safety, and this is a good reason, but it is definitely not the only one. The big problem with using scripts to generate the code is that it distributes the complex work during the build cycle and all the programmers using it. That is, even when a script is running, a programmer using a script should be reasonably aware of its existence. The build cycle has to be written in order to keep abreast of the script, and debugging with script-generated code is also relatively complex because you are debugging code that neither you nor any other person actually wrote. The script generated code is rarely written like an ordinary person will write the same thing, which makes it twice difficult to debug.

- , , . , : , ( , ) , / . , , , , .

, , , , . , , , , . , , ; .

, , . . TMP TMP . , . script, , script - .., , , , , , .

+7

:

- , ( ) [...]

So script , .

++ , ++.

+3

?

, . .

+2

[] - ?

Take a look at the following metaprogram. It overloads operator<<for any array Ts, except when it Tis a type char. (Without this precaution, outputting string literals will no longer work.)

template <typename T, size_t n>
typename disable_if<
    is_same<typename remove_const<T>::type, char>::value,
    std::ostream&
>::type
operator<<(std::ostream& os, T (&array)[n])
{
    return print_range(os, array + 0, array + n);
}

So, how would you “pin” this metaprogram? Create real code for all possible types T? This is not possible because you do not know the "scripting time" whose types will exist at compile time.

+1
source

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


All Articles