c++ - 如何强制 C++ 预处理器宏中的特定类型?
问题描述
我正在尝试通过预处理器宏生成一个静态变量以用于记录目的。该变量用作计数器已发送特定消息的频率。为了使这个线程安全,我想从使用int
计数器切换到std::atomic<int>
- 在大多数编译器上都可以正常工作:
#define GENERATE_LOG_VAR(Count) static std::atomic<int> local___FUNCTION__##Count##__LINE__ = std::atomic<int>(Count)
#define GET_LOG_VARIABLE(Count) local___FUNCTION__##Count##__LINE__
但是,在 GCC 7.3.1 上,我收到以下错误:
error: use of deleted function 'std::atomic<int>::atomic(const std::atomic<int>&)'
#define GENERATE_LOG_VAR(Count) static std::atomic<int> local___FUNCTION__##Count##__LINE__ = std::atomic<int>(Count)
^
note: in expansion of macro 'GENERATE_LOG_VAR'
GENERATE_LOG_VAR(max_log_count); \
^~~~~~~~~~~~~~~~
note: declared here
atomic(const atomic&) = delete;
^~~~~~
所以我知道编译器以某种方式解释Count
为std::atomic<int>
并试图调用似乎被删除的复制构造函数。但是我该如何规避这个问题呢?
我已经尝试过简单地分配Count
非常相似的结果:
error: use of deleted function 'std::atomic<int>::atomic(const std::atomic<int>&)'
#define GENERATE_ONCE GENERATE_LOG_VAR(1)
^
note: in definition of macro 'GENERATE_LOG_VAR'
#define GENERATE_LOG_VAR(Count) static std::atomic<int> local___FUNCTION__##Count##__LINE__ = Count
^~~~~
note: declared here
atomic(const atomic&) = delete;
^~~~~~
note: after user-defined conversion: constexpr std::atomic<int>::atomic(std::atomic<int>::__integral_type)
constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { }
^~~~~~
所以我的问题是
- 如何强制编译器解释
Count
为int
?或者 - 否则我该如何解决?
解决方案
您应该将宏更改为
#define GENERATE_LOG_VAR(Count) static std::atomic<int> local___FUNCTION__##Count##__LINE__(Count)
这将避免构建副本,或尝试构建副本,或在这种情况下准确的标准语所说的任何内容。
推荐阅读
- python - 如何在python3中使用re仅打印所需的单词
- javascript - PassportJS 身份验证每次都失败(LocalStrategy)
- postgresql - 在 postgresql 中测量复制滞后
- r - 带有插入符号的 R 特征选择 - 将结果图限制在前 10 位,并将完整结果存储到数据框中
- sapui5 - SAP UI5 值帮助仅适用于 Smartfield
- excel-formula - 选择 Randbetween 函数给我一个#NAME?Excel中的错误
- python - Pandas 中的子集分层索引和分层列名(有和没有索引)
- swift - 如何在依赖firebase API的ios项目上实现测试
- jquery - 数据表未填充 .html() 生成的表
- html - ASP Net Core Angular - 使用 bootstrap 4 而不是 3 (SideMenu) 的默认项目