首页 > 解决方案 > 如何强制 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;
       ^~~~~~

所以我知道编译器以某种方式解释Countstd::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) { }
                 ^~~~~~

所以我的问题是

标签: c++

解决方案


您应该将宏更改为

#define GENERATE_LOG_VAR(Count) static std::atomic<int> local___FUNCTION__##Count##__LINE__(Count)

这将避免构建副本,或尝试构建副本,或在这种情况下准确的标准语所说的任何内容。


推荐阅读