C++宏定义和取消定义

C++ Macro define and undefine

本文关键字:定义 取消 宏定义 C++      更新时间:2023-10-16

我想使用宏在标头中快速创建内联函数,这些函数与我正在子类化的基类有关。我将定义放在基类标头中,但我不想用所有宏定义污染包含这些标头的所有内容,所以我想写这样的东西(不幸的是不起作用(:

#define BEGIN_MACROS 
#define MACRO_1(...) ...
#define MACRO_2(...) ...
#define MACRO_3(...) ...
#define END_MACROS 
#undef MACRO_1
#undef MACRO_2
#undef MACRO_3

然后像这样使用它:

BEGIN_MACROS
MACRO_1(...)
MACRO_2(...)
MACRO_3(...)
END_MACROS

也许我应该使用这样的东西吗?

#include "definemacros.h"
MACRO_1(...)
MACRO_2(...)
MACRO_3(...)
#include "undefmacros.h"

并将定义和"取消定义"放在两个单独的标题中......

还是有更好的方法来克服这类问题? 还是您建议避免在标题中使用宏和/或宏?

经过编辑以包含特定用例:

定义:

#define GET_SET_FIELD_VALUE_INT(camelcased, underscored)
inline int rget ## camelcased () { return this->getFieldValue( #underscored ).toInt(); }
inline void rset ## camelcased (int value) { this->setFieldValue( #underscored , value); }

用:

class PaymentRecord : public RecObj
{
public:
GET_SET_FIELD_VALUE_INT(PriceIndex, price_index)
//produces this
inline int rgetPriceIndex() { return this->getFieldValue("price_index").toInt(); }
inline void rsetPriceIndex(int value) { this->setFieldValue("price_index", value); }
};

你不能将更多的定义堆叠成一行(至少据我所知......我要做的是将它们封装到 2 个单独的文件中,而不是像这样:

文件 macro_beg.h:

#define MACRO_1(...) ...
#define MACRO_2(...) ...
#define MACRO_3(...) ...

文件 macro_end.h:

#undef MACRO_1
#undef MACRO_2
#undef MACRO_3

就像您的第二种情况一样,但宏不在单行中......

#include "macro_beg.h"
MACRO_1(...);
MACRO_2(...);
MACRO_3(...);
#include "macro_end.h"

但正如一些程序员所评论的那样,这可能无法正常工作或根本无法工作,具体取决于编译器预处理器和宏复杂性或使用类/模板代码嵌套。但是对于简单的东西,这应该可以工作。