c++ - 不使用标识符重复类实例化

标签 c++ unique anonymous

我想在模块范围内重复实例化一个类,而不提供唯一名称。像这样。

MyClass name##__LINE__(); // doesn't work because __LINE__ won't stringify
MyClass name##__LINE__(); // duplicate identifier error - two name__LINE__ variables

有没有办法做到这一点,要么创建一个唯一的名称,要么使用一些匿名上下文,例如初始化程序或结构?

最佳答案

参见 this answer

#define CONCATENATE_DETAIL(x, y) x##y
#define CONCATENATE(x, y) CONCATENATE_DETAIL(x, y)
#define MAKE_UNIQUE(x) CONCATENATE(x, __LINE__)

MyClass MAKE_UNIQUE(name);
MyClass MAKE_UNIQUE(name);
...

或者只是做一个数组:

MyClass arr[N];

为什么这些宏有效
C11 标准,6.10.3.1 参数替换:

After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.

C++ 标准中的相应段落(16.3.1 参数替换)是 C 标准的精确拷贝。

关于c++ - 不使用标识符重复类实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26049998/

相关文章:

MySQL:对行组合设置唯一限制的问题

c# - 如何字符串字段是唯一的 mvc 5 asp.net

r - 具体用 R 删除所有重复项

object - PL/SQL 在匿名 block 中创建对象

c++ - 为什么编译器推迟 std::list 释放?

c++ - LuaL_openlibs() 和沙盒脚本

c++ - 如何创建一个从两侧都可见的四边形?

c++ - 容器的 begin() 和 end() 的不同实现

java - 对象创建优化

javascript - Firebase:在 cookie 中存储匿名身份验证