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

2019-01-09 09:00发布

问题:

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

#include <iostream>   

#ifdef NOOP       
    #define conditional_noop(x) what goes here?   
#else       
    #define conditional_noop(x) std::cout << (x)   
#endif   
int main() {       
    conditional_noop(123);   
}

I want this to do nothing when NOOP is defined and print "123", when NOOP is not defined.

回答1:

As mentioned before - nothing.
Also, there is a misprint in your code.
it should be #else not #elif. if it is #elif it is to be followed by the new condition

#include <iostream>   

#ifdef NOOP       
    #define conditional_noop(x) do {} while(0)
#else       
    #define conditional_noop(x) std::cout << (x)   
#endif  

Have fun coding! EDIT: added the [do] construct for robustness as suggested in another answer.



回答2:

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).



回答3:

 #ifdef NOOP       
     #define conditional_noop(x)   
 #elif  

nothing!



回答4:

Defining the macro to be void conveys your intent well.

#ifdef NOOP
    #define conditional_noop(x) (void)0
#else


回答5:

#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.



回答6:

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



回答7:

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.



回答8:

As this is a macro, you should also consider a case like

if (other_cond)
    conditional_noop(123);

to be on the safe side, you can give an empty statement like

#define conditional_noop(X) {}

for older C sometimes you need to define the empty statment this way (should also get optimized away):

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


回答9:

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.