【发布时间】:2015-05-27 07:30:52
【问题描述】:
这是我第一次遇到这种类型的代码。我很难理解它。
#ifndef A
#define A
#endif
#ifndef B
#define B
#endif
void funct (structA* A paramA, structB* B paramB){};
参数中预处理器A和B的作用是什么?
【问题讨论】:
这是我第一次遇到这种类型的代码。我很难理解它。
#ifndef A
#define A
#endif
#ifndef B
#define B
#endif
void funct (structA* A paramA, structB* B paramB){};
参数中预处理器A和B的作用是什么?
【问题讨论】:
为:
#define A this_is_a
预处理器会将A 替换为this_is_a。
为:
#define A
预处理器会将A 替换为空。
因此,在您的示例代码中,A 和 B 符号将被丢弃。人们有时会使用这种技术来注释代码,例如:
#define IN
#define OUT
现在您可以注释函数参数,显示它们是“输入”还是“输出”参数:
void my_function(IN int i, OUT int& x) { ... }
【讨论】:
你可以这样做(假设你的代码在foo.h):
#include "foo.h"
...
#define A const
#include "foo.h"
基本上,您的代码所做的是它允许向参数添加标志。如果包含标头时未定义A 宏,则将其定义为空字符串,因此将其忽略。但是,如果定义了宏,则将其值代入签名中。
另一种用法是根据编译器功能选择功能。例如:
#ifdef HAVE_CPP11
# define FORWARD_REF &&
# define FORWARD(T, x) std::forward<T>(x)
#else
# define FORWARD_REF const &
# define FORWARD(T, x) x
#endif
template <typename T>
void function_that_forwards_parameter(T FORWARD_REF t) {
foo(FORWARD(T, t));
}
【讨论】: