c++ - 我可以对宏使用哪些技巧?

标签 c++ c c-preprocessor stringification

在我们的遗留代码以及现代代码中,我们使用宏来执行代码生成等漂亮的解决方案。我们同时使用 ### 运算符。

我很好奇其他开发人员如何使用宏来做很酷的事情,如果他们使用宏的话。

最佳答案

在 C 中,通常定义宏来执行某些操作以获取逐字参数,同时定义能够透明地获取其地址的函数。

// could evaluate at compile time if __builtin_sin gets
// special treatment by the compiler
#define sin(x) __builtin_sin(x)

// parentheses avoid substitution by the macro
double (sin)(double arg) {
    return sin(arg); // uses the macro
}

int main() {
    // uses the macro
    printf("%f\n", sin(3.14));

    // uses the function
    double (*x)(double) = &sin;

    // uses the function
    printf("%f\n", (sin)(3.14));
}

关于c++ - 我可以对宏使用哪些技巧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/650461/

相关文章:

c - C中错误自动调整数组长度

c++ - 哈希符号 + 数字 "# 1"形式的 gcc 预处理输出行是什么意思?

c++ - 如何在 C++ 中检索基类的类型?

c++ - .cpp 文件中函数的多个定义

c++ - 使用 C++ Code::Blocks 将文本文件中的单独部分读入 vector

c++ - 队列实现的 Malloc 指针错误

C++ - 堆栈 Pop() 函数与单链表

c - 在迷宫中寻找路径时出现段错误

C 多维数组不接受对其成员的修改

c - 神秘的大小写常量定义多次错误