How I can compile template function with pre-processor condition? Like that (but it is not working):
template
void f()
{
#if (var == tru
You can't. The preprocessor, as this names indicates, processes the source file before the compiler. It has therefore no knowledge of the values of your template arguments.
If you need to generate different code paths with template parameter, you can just simply use if
or other C++ statement:
template <bool var>
void f()
{
if (var == true) {
// ...
}
}
Compiler can optimize it and generate code that doesn't contain such branches.
A little drawback is that some compiler (e.g. Msvc) will generate warnings for conditions which is always constant.
With C++17's introduction of if constexpr you can discard branches inside a template, much like conditional compilation allows.
template <bool var>
void f()
{
if constexpr (var == true) {
// ...
}
}
The code inside the branch has to be syntactically correct, but doesn't have to be well-formed when var
is false, because it will be discarded entirely.
You can't do that with the preprocessor. All you can do is delegate the code to 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 likely), you have to pass it as parameters. Or make only_if_true
a class and store the shared data in it.