Preprocessor and template arguments or conditional compilation of a code snippet

How can I compile a template function with a pre-processor condition? Like this (but it doesn't work):

template <bool var> void f() { #if (var == true) // ... #endif } 
+5
source share
4 answers

You can not. The preprocessor, as these names indicate, processes the source file before the compiler. Therefore, it does not know the meaning of your template arguments.

+9
source

You cannot do this with a preprocessor. All you can do is delegate the code into a separate template, something like this:

 template <bool var> void only_if_true() {} template <> void only_if_true<true>() { your_special_code_here(); } template <bool var> void f() { some_code_always_used(); only_if_true<var>(); some_code_always_used(); } 

Of course, if you need information shared between f() and only_if_true() (which is quite likely), you should pass it as parameters. Or make only_if_true class and save the general data in it.

+7
source

If you need to create different code paths with a template parameter, you can simply use if or another C ++ operator:

 template <bool var> void f() { if (var == true) ο½› // ... } } 

The compiler can optimize it and generate code that does not contain such branches.

A minor flaw is that some compiler (e.g. Msvc) generates warnings for conditions that are always constant.

+3
source

With the advent of if constexpr in C ++ 17, you can drop branches inside a template, as conditional compilation allows.

 template <bool var> void f() { if constexpr (var == true) { // ... } } 

The code inside the branch should be syntactically correct, but should not be correctly formed when var false, because it will be completely discarded.

0
source

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


All Articles