C++宏

C++宏

C++ 中的宏常用于条件编译与防卫式声明等场景,而定义常量及短函数,出于类型检查方面考虑,并不推荐使用宏;

但是有两种宏的使用方式可简洁实现复杂功能,推荐使用,示例如下:

转为字符串

示例代码:

#include <iostream>

#define PRINT_DEBUG(x)  \
std::cout << #x << " = " << x << std::endl

int main()
{
    double v = 5;
    PRINT_DEBUG(v);

    return 0;
}

结果输出:

v = 5

拼接标识符

示例代码:

#include <iostream>

#define CALL_FUNC(index) func_##index

void func_1()
{
    std::cout << "call func_1" << std::endl;
}

void func_2()
{
    std::cout << "call func_2" << std::endl;
}

void func_3()
{
    std::cout << "call func_3" << std::endl;
}

int main()
{
    CALL_FUNC(1)();

    return 0;
}

结果输出:

call func_1

小结

上述代码中,对于转为字符串与拼接标识符这两种功能仅仅是简单示例,在实际编码中,如若恰当使用宏的这两种功能,可达到事半功倍的效果;


本文作者: 王同学