gpt4 book ai didi

c++ - 格式化宏以使用单行 if 语句

转载 作者:行者123 更新时间:2023-11-30 04:58:27 25 4
gpt4 key购买 nike

我正在使用 boost 日志记录框架,这可能与这个问题无关,但我想要一个 LOG(sev) 形式的宏,其中 sev是日志级别之一,我可以标准化输出的格式。

#define LOG_LOCATION \
boost::log::attribute_cast<boost::log::attributes::mutable_constant<int>>(boost::log::core::get()->get_global_attributes()["Line"]).set(__LINE__); \
boost::log::attribute_cast<boost::log::attributes::mutable_constant<std::string>>(boost::log::core::get()->get_global_attributes()["File"]).set(__FILE__); \
boost::log::attribute_cast<boost::log::attributes::mutable_constant<std::string>>(boost::log::core::get()->get_global_attributes()["Function"]).set(__func__);

#define LOG(sev) LOG_LOCATION BOOST_LOG_SEV(slg, sev)

extern boost::log::sources::severity_logger<boost::log::trivial::severity_level > slg;

此代码片段适用于日志位于单行的大多数情况,但是,如果我在格式中使用 if。

if(false) LOG(debug) << "Don't print this";

它总是打印消息。原因很明显,if 应用于宏中的第一条语句并执行其余语句,因此该语句将显示(没有行号)。

我不确定如何格式化此宏才能正常工作。

最佳答案

替换 LOG_LOCATION 中三个函数调用末尾的分号带逗号的宏。这会将三个语句变成一个部分语句,在展开的宏结束后继续。

#define LOG_LOCATION \
boost::log::attribute_cast<boost::log::attributes::mutable_constant<int>>(boost::log::core::get()->get_global_attributes()["Line"]).set(__LINE__), \
boost::log::attribute_cast<boost::log::attributes::mutable_constant<std::string>>(boost::log::core::get()->get_global_attributes()["File"]).set(__FILE__), \
boost::log::attribute_cast<boost::log::attributes::mutable_constant<std::string>>(boost::log::core::get()->get_global_attributes()["Function"]).set(__func__),

如上所示使用时,if行会变成

if(false) a, b, c, BOOST_LOG_SEV(slg, sev) << "Don't print this";

(为简洁起见,将对 set 的三个调用替换为字母。)

如果 BOOST_LOG_SEV 这会起作用扩展为单个表达式。然而,BOOST_LOG_SEV扩展为 for声明:

for (::boost::log::record rec_var = (logger).open_record((BOOST_PP_SEQ_ENUM(params_seq))); !!rec_var;)
::boost::log::aux::make_record_pump((logger), rec_var).stream()

因此需要一种不同的方法。

您可以将“LOG”定义为类(而不是宏),以将所有内容封装在这些宏中。

class LOG {
public:
LOG(int sev): sev(sev) { LOG_LOCATION; }
LOG &operator<<(const char *msg) {
BOOST_LOG_SEV(slg, sev) << msg;
return *this;
}
}

根据您的需要,您可以添加 operator<< 的其他重载处理std::string , int ,或者只是将其设为模板类。

在发送多个项目时,这可能不如原来的效率高 (LOG(debug) << "Number " << x << " found."),但可以作为单个语句使用。

关于c++ - 格式化宏以使用单行 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51665433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com