c++ - 在 C++ 中将函数实现为宏的优点/缺点

标签 c++ macros

将业务逻辑函数实现为宏是个好主意吗?

我继承了一些遗留的 C++ 代码,我发现很多业务逻辑函数都是作为长而神秘的宏实现的。

宏比函数有优势吗? 使用宏背后的一般原理是什么?

哪种逻辑最适合宏?

这是一个简单的代码示例

#define INSERT_VALUES(IN,ID,EO)     {\
    double evaluationOutput = EO;\
    int controls = 0;\
    int input_controls = m_input_controls[IN];\
    if(m_value_list[IN].ShouldProcess())\
        {\
        evaluationOutput = m_evaluationOutput[IN];\
        controls = m_controls[IN];\
        }\
    VALUE_EXIST(evaluationOutput,controls,input_controls,IN,ID,Adj);\
    m_evaluationOutput[IN] = controls > 0 ? evaluationOutput : 0.0;\
    m_controls[IN] = controls;\
    m_input_controls[IN] = input_controls;\                                 
}

最佳答案

Effective C++ ,Scott Meyers 在第 2 项中指出:

Prefer consts, enums, and inlines to #defines

Meyers 特别提到了编写宏而不是函数的做法:

Another common (mis)use of the #define directive is using it to implement macros that look like functions but don't incur the overhead of a function call.

Macros like this have so many drawbacks, just thinking about them is painful.

Fortunately, you don't have to put up with this nonsense. You can get all the efficiency of a macro plus all the predictable behavior and type safety of a regular function by using a template for an inline function.

[Real functions] obey scope and access rules. For example, it makes perfect sense to talk about an inline function that is private to a class. In general, there's just no way to do that with a macro.

具体回答您的问题:

  • 一些程序员编写宏而不是函数来避免函数调用的开销——这是一种可疑的做法,通常没有什么可衡量的好处。
  • 程序员过去常常使用预处理器来生成样板代码(也许现在仍然如此)。在现代 C++ 中,处理器的使用应限于 #include 和(可能)#ifdef/#ifndef 以进行条件编译。

正如迈耶斯在结束时指出的那样:

It's not yet time to retire the preprocessor, but you should definitely give it long and frequent vacations.

关于c++ - 在 C++ 中将函数实现为宏的优点/缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305844/

相关文章:

rust - 检查宏中定义的项目中的功能标志

c++ - 如何将宏中#define 的值转换为 char* (c++)

c++ - 用于存储和搜索比赛结果的数据结构

c++ - C/C++ 中的自展开宏循环

c - 在调试符号中显示宏(嵌入式)

c++ - 无法使用辅助链表合并排序链表

c - 如何在 C 中获取函数参数的指针?

c++ - "Overriding"ostream& 运算符<<

c++ - 重构 id 类型

c++ - 生成代码以实例化具有不同参数的函数模板