Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor and template arguments or conditional compilation of piece of code

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
}
like image 764
4Bytes Avatar asked Nov 14 '12 11:11

4Bytes


People also ask

What is the use of conditional compilation?

Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.

What is the role of compiler by templates?

Compiler creates a new instance of a template function for every data type. So compiler creates two functions in the above example, one for int and other for double. Every instance has its own copy of static variable. The int instance of function is called twice, so count is incremented for the second call.

What are templates and how does the compiler interpret them?

In other words, a template is a mechanism that allows a programmer to use types as parameters for a class or a function. The compiler then generates a specific class or function when we later provide specific types as arguments.


1 Answers

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.

like image 62
slaphappy Avatar answered Oct 05 '22 13:10

slaphappy