Preprocessor and template arguments or conditional compilation of piece of code

前端 未结 4 921
抹茶落季
抹茶落季 2021-01-18 19:05

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

template 
void f()
{
    #if (var == tru         


        
相关标签:
4条回答
  • 2021-01-18 19:15

    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.

    0 讨论(0)
  • 2021-01-18 19:21

    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.

    0 讨论(0)
  • 2021-01-18 19:21

    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.

    0 讨论(0)
  • 2021-01-18 19:34

    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.

    0 讨论(0)
提交回复
热议问题