Preprocessor and template arguments or conditional compilation of piece of code

丶灬走出姿态 提交于 2019-12-19 21:21:12

问题


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
}

回答1:


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.




回答2:


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.




回答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.




回答4:


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.



来源:https://stackoverflow.com/questions/13378025/preprocessor-and-template-arguments-or-conditional-compilation-of-piece-of-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!