使用来自 const 成员函数的每个类 boost::log::sources::logger
-
15-11-2019 - |
题
我想要每个类都有一个日志源,就像来自的 basic_logger 示例 文档
这是可行的,但是当从 const 成员函数记录某些内容时,我收到一个编译器错误,抱怨常量性,如下所示:
#include "boost/log/sources/channel_logger.hpp"
#include "boost/log/common.hpp"
#include "boost/log/utility/init/to_console.hpp"
#include "boost/log/utility/init/common_attributes.hpp"
class Test
{
public:
// this works, not a const function
void test1()
{
BOOST_LOG(m_logger) << "Test 1";
}
// this will not compile, const function
void test2() const
{
BOOST_LOG(m_logger) << "Test 2";
}
private:
boost::log::sources::channel_logger<std::string> m_logger;
};
int main()
{
boost::log::add_common_attributes();
boost::log::init_log_to_console();
Test t;
t.test1();
t.test2();
return 1;
}
在这个例子中 Test::test2
给出编译错误,因为它的 const 和 m_logger
不是。 Test::test1
工作正常。
如何以干净的方式解决这个问题而不需要 const_cast
, mutable
ETC。
解决方案
如果日志存储在类中,那么当然不能在类中修改它 const
语境。
我知道你要求的是别的东西,但老实说我认为 mutable
是这里合适的解决方案。这正是用例,这就是为什么 mutable
存在。
其他提示
您需要将可变记录器移到类之外,然后一切都会正常工作。或者您使用不同的东西来为您提供不可变的记录器对象。
不隶属于 StackOverflow