Preprocessor and template arguments or conditional compilation of piece of code

前端 未结 4 965
抹茶落季
抹茶落季 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: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 
    void only_if_true()
    {}
    
    template <>
    void only_if_true()
    {
      your_special_code_here();
    }
    
    
    template 
    void f()
    {
      some_code_always_used();
      only_if_true();
      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.

提交回复
热议问题