#define在C ++中的一个合适的使用场景是什么? [英] What is an appropriate use scenario of #define in C++?
问题描述
我知道基本规则,使用 inline
, enum
和 const
而不是 #define
,这不是我跟这个问题。我想知道的是什么被认为是一个可接受的场景,其中你会使用一个 #define
宏,以及如何,在C ++。
I know the basic rules, use inline
, enum
and const
instead of #define
, that is not what I'm after with this question. What I want to know is what is considered an acceptable scenario in which you would use a #define
macro, and how, in C++.
请不要提出问题或链接到define VS const问题或预处理器VS编译器,我已经经历了Effective C ++ by Scott
然而经过几个小时和几个小时的网上冲浪,我得到的感觉#define被视为在C ++中的某种弱者,但我确信必须有一种情况下,它是可以接受的,甚至是可取的,使用它。
However after hours and hours of surfing the net, I get the feeling #define is treated as some kind of underdog in C++, but I'm sure there must be a case in which it could be acceptable, even desirable, to use it.
为了滚动滚动我想一个我可以想到的一个场景是创建一个 DEBUG
To get the ball rolling I guess one scenario I could think of is to create a DEBUG
macro that based on it enables prints and whatnot all over the code for debug purposes.
推荐答案
这里有几个场景,其中使用#define是一个很好的解决方案:
Here are a few scenarios where using #define is a good solution:
添加诊断信息,同时保留函数签名:
Adding diagnostics information while preserving function signature:
#ifdef _DEBUG
#define Log(MSG) Log((MSG), __FILE__, __LINE__);
#endif
条件编译和包含保护也是一个很好的例子因为你应该明白这一点:))。
Conditional compilation and include guards are also a good example (no example given, as you should understand this :)).
Boilerplate代码是另一个例子,但是这很容易被滥用。使用宏作为样板代码的一个好例子是Boost.UnitTest中的BOOST_AUTO_TEST_CASE宏(更糟的例子是将Windows API映射到其CHAR或WCHAR宏的WinAPI宏集)。
Boilerplate code is another example, but this can easily be abused. A good example of using macros for boilerplate code is the BOOST_AUTO_TEST_CASE macro in Boost.UnitTest (a worse example is the WinAPI macro set that maps Windows APIs to their CHAR or WCHAR macros).
另一个很好的例子是提供编译器特定的关键字和设置:
Another good example is providing compiler-specific keywords and settings:
#if (defined _WIN32) && (defined LIB_SHARED)
# ifdef LIB_EXPORTS
# define LIB_EXPORT __declspec(dllexport)
# else
# define LIB_EXPORT __declspec(dllimport)
# endif /* LIB_EXPORTS */
#else
# define LIB_EXPORT extern
#endif /* _WIN32 && LIB_SHARED */
用法:
// forward declaration of API function:
LIB_EXPORT void MyFunction(int);
这篇关于#define在C ++中的一个合适的使用场景是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!