Alex Rivera | Logout

Preprocessor and template arguments or conditional compilation of piece of code

Asked 2012-11-14T11:32:53.503
9

How I can compile template function with pre-processor condition? Like that (but it is not working):

template <bool var>
void f()
{
    #if (var == true)
    // ...
    #endif
}
Edit
Report

2 Answers

9

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.

answered 2012-11-14T11:35:49.010
3

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.

answered 2012-11-14T12:04:31.437

Your Answer