预处理器:插入结构名称中的前一个行号

Preprocessor: concat previous line number in the name of a structure

本文关键字:一个 插入 处理器 结构 预处理      更新时间:2023-10-16

我知道如何声明一个结构,其中名称包含当前行号。以下代码按预期工作。

#define CREATE_NAME_CONCAT_(X, Y) X ## Y
#define CREATE_NAME_CONCAT(X, Y) CREATE_NAME_CONCAT_(X, Y)
#define CREATE_FOO_NAME CREATE_NAME_CONCAT(Foo_, __LINE__)
struct CREATE_FOO_NAME { int x; };
typedef Foo_4 Foo;
int main()
{
Foo foo;
foo.x = 42; 
return 0;
}

如何使用前一个行号编写typedef行以下代码不起作用:

#define CREATE_NAME_CONCAT_(X, Y) X ## Y
#define CREATE_NAME_CONCAT(X, Y) CREATE_NAME_CONCAT_(X, Y)
#define CREATE_FOO_NAME CREATE_NAME_CONCAT(Foo_, __LINE__)
struct CREATE_FOO_NAME { int x; };
typedef CREATE_NAME_CONCAT(Foo_, __LINE__-1) Foo;
int main()
{
Foo foo;
foo.x = 42; 
return 0;
}

注意1:是的,我有充分的理由这么做

注意2:我不使用C++11或更新的

注3:我不想辩论注1&2

预处理器非常有限,最好的解决方案是根本不使用它。你可以用模板完成类似的事情:

template <int>
struct FooT;
template <>
struct FooT<__LINE__> { int x; };
typedef FooT<__LINE__-1> Foo;
int main()
{
Foo foo;
foo.x = 42; 
return 0;
}

我不知道这是否符合你的要求,因为它们似乎是秘密。