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

2019-01-09 08:49发布

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.

9条回答
Deceive 欺骗
2楼-- · 2019-01-09 09:08

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

查看更多
男人必须洒脱
3楼-- · 2019-01-09 09:13
 #ifdef NOOP       
     #define conditional_noop(x)   
 #elif  

nothing!

查看更多
Evening l夕情丶
4楼-- · 2019-01-09 09:16

Defining the macro to be void conveys your intent well.

#ifdef NOOP
    #define conditional_noop(x) (void)0
#else
查看更多
淡お忘
5楼-- · 2019-01-09 09:19

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.

查看更多
Viruses.
6楼-- · 2019-01-09 09:21
#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.

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-09 09:21

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.

查看更多
登录 后发表回答