C++宏定义和取消定义
C++ Macro define and undefine
我想使用宏在标头中快速创建内联函数,这些函数与我正在子类化的基类有关。我将定义放在基类标头中,但我不想用所有宏定义污染包含这些标头的所有内容,所以我想写这样的东西(不幸的是不起作用(:
#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"
但正如一些程序员所评论的那样,这可能无法正常工作或根本无法工作,具体取决于编译器预处理器和宏复杂性或使用类/模板代码嵌套。但是对于简单的东西,这应该可以工作。
相关文章:
- C++宏定义和取消定义
- C++错误:在类中取消对main的定义引用
- 在宏中定义然后取消定义预处理器变量
- 如何在不取消定义类型的情况下为 C++ 中的类型编写 getter?
- 取消脱壳:使用模板在多行类型定义中添加一个尖括号后的新行
- 在自定义双链接列表中的自定义迭代器的取消运算符,找不到二进制操作员
- 如果我返回const定义的对象,为什么const关键字被取消资格
- 在Ubuntu 12.04.1 LTS libssl-libcrypto上取消定义引用
- 正在取消引用自定义结构字段的迭代器
- 取消定义引用..:从模板类继承
- 自定义 std::shared_ptr 或 boost::shared_ptr 以在 NULL 取消引用时引发异常
- 为什么我的指针在 main 中取消引用后具有不同的值,而不是在我自己的自定义函数中取消引用它时?
- 关于智能指针中取消引用和成员选择运算符的定义
- 我可以显式取消定义特定函数的宏吗?
- 取消引用悬空指针是否是未定义的行为
- 取消引用等于 nullptr 的指针是否是标准的未定义行为?
- C++/Qt定义/取消定义Qt_NO_SESSIONMANAGER宏
- 需要一个头文件,取消定义在windows.h中的所有定义
- 在取消定义宏函数之前,在宏函数中使用/复制宏变量的值:可能吗?
- #定义/#取消定义一个具有特殊含义的标识符是未定义的行为吗