用宏定义实现自增变量

在使用 C++ 语音编程时,有时需要一些自增变量,比如:

static constexpr auto FLAG_A = 1;
static constexpr auto FLAG_B = 2;
static constexpr auto FLAG_C = 3;
static constexpr auto FLAG_D = 4;

这个时候,如果用一个宏比如 IOTA() 来代表自增变量会方便很多:

static constexpr auto FLAG_A = IOTA();
static constexpr auto FLAG_B = IOTA();
static constexpr auto FLAG_C = IOTA();
static constexpr auto FLAG_D = IOTA();

下面定义了两个宏:IOTA_START()IOTA()

#define IOTA_START() static const int __counter__ = __LINE__
#define IOTA() ( __LINE__ - __counter__ - 1 )

其基本原理是通过行号 __LINE__ 计算得到一个按行自增的值。

使用方式:

#define IOTA_START() static const int __counter__ = __LINE__
#define IOTA() ( __LINE__ - __counter__ - 1 )

IOTA_START();
static constexpr auto FLAG_A = IOTA();
static constexpr auto FLAG_B = IOTA();
static constexpr auto FLAG_C = IOTA();
static constexpr auto FLAG_D = IOTA();

示例:

#include <iostream>

#define IOTA_START() static const int __counter__ = __LINE__
#define IOTA() ( __LINE__ - __counter__ - 1 )

IOTA_START();
static const int FLAG_A = IOTA();
static const int FLAG_B = IOTA();
static const int FLAG_C = IOTA();
static const int FLAG_D = IOTA();

int main(int argc, char* argv[]) {
    std::cout << "FLAG_A: " << FLAG_A << std::endl;
    std::cout << "FLAG_B: " << FLAG_B << std::endl;
    std::cout << "FLAG_C: " << FLAG_C << std::endl;
    std::cout << "FLAG_D: " << FLAG_D << std::endl;
    return 0;
}

输出:

FLAG_A: 0
FLAG_B: 1
FLAG_C: 2
FLAG_D: 3