using per class boost::log::sources::logger from const member function
I want a log source per class like the basic_logger example from the docs
This works but I get a compiler error complaining about the constness when logging something from a const member function like so:
#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;
}
In this example Test::test2
gives a compile error because its const and m_logger
is not. Test::test开发者_如何学Python1
works fine.
How can this be fixed in a clean way without const_cast
, mutable
etc.
If the log is stored in the class, then of course you cannot modify it in a const
context.
I realise that you asked for something else, but I honestly think that mutable
is the appropriate solution here. This is exactly the use case that is why mutable
exists.
You need to move the mutable logger outside of your class then all will work fine. Or you use something different which gives you an immutable logger object.
精彩评论