How do I implement no-op macro (or template) in C++?

后端 未结 9 1930
谎友^
谎友^ 2020-12-01 11:53

How do I implement no-op macro in C++?

#include    

#ifdef NOOP       
    #define conditional_noop(x) what goes here?   
#else       
    #         


        
相关标签:
9条回答
  • 2020-12-01 12:30
    #ifdef NOOP
        static inline void conditional_noop(int x) { }
    #else 
        static inline void conditional_noop(int x) { std::cout << x; }
    #endif
    

    Using inline function void enables type checking, even when NOOP isn't defined. So when NOOP isn't defined, you still won't be able to pass a struct to that function, or an undefined variable. This will eventually prevent you from getting compiler errors when you turn the NOOP flag on.

    0 讨论(0)
  • 2020-12-01 12:30

    You can just leave it blank. You don't need to follow the #define with anything.

    0 讨论(0)
  • 2020-12-01 12:34

    While leaving it blank is the obvious option, I'd go with

    #define conditional_noop(x) do {} while(0)
    

    This trick is obviously no-op, but forces you to write a semicolon after conditional_noop(123).

    0 讨论(0)
  • 2020-12-01 12:35

    Defining the macro to be void conveys your intent well.

    #ifdef NOOP
        #define conditional_noop(x) (void)0
    #else
    
    0 讨论(0)
  • 2020-12-01 12:43

    Like others have said, leave it blank.

    A trick you should use is to add (void)0 to the macro, forcing users to add a semicolon after it:

    #ifdef NOOP       
        #define conditional_noop(x) (void)0
    #else       
        #define conditional_noop(x) std::cout << (x); (void)0
    #endif  
    

    In C++, (void)0 does nothing. This article explains other not-as-good options, as well as the rationale behind them.

    0 讨论(0)
  • 2020-12-01 12:50

    I think that a combination of the previous variants is a good solution:

    #ifdef NOOP
        static inline void conditional_noop(int x) do {} while(0)
    #else 
        static inline void conditional_noop(int x) do { std::cout << x; } while(0)
    #endif
    

    The good thing is that these two codes differ only inside a block, which means that their behaviour for the outside is completely identical for the parser.

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