【问题标题】:Boost.Log ignores overloaded stream insertion operatorBoost.Log 忽略重载的流插入操作符
【发布时间】:2014-04-10 09:38:32
【问题描述】:

我有一个类,我想以某种方式出现在日志中,所以我重载了它的 << 运算符:

class CWindowClassId
{
public:
    // ...
    friend std::wostream& operator<< (std::wostream& os, CWindowClassId const& classId);
}

在日志流中插入上面的类:

// ...
CWindowClassId classId(hWindow);
BOOST_LOG_TRIVIAL(debug) << "Window created, class = " << classId;

导致编译错误:

Error   1   error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const Sandbox::CWindowClassId' (or there is no acceptable conversion)    C:\local\boost_1_55_0\boost\log\utility\formatting_ostream.hpp  710

我知道错误在于,我为宽字符串重载了 &lt;&lt;。当我使用ostream 而不是wostream 时一切都很好,但我真的很想使用宽字符串版本。

我尝试为接收器设置区域设置:

shared_ptr<log::sinks::synchronous_sink<log::sinks::text_file_backend> > sink = log::add_file_log("log.txt");
sink->imbue(boost::locale::generator()("en_US.UTF-8"));

并且在任何与日志相关的包含之前定义BOOST_LOG_USE_WCHAR_T

我可以做些什么来使用宽字符串&lt;&lt; 运算符进行日志记录?

我使用的是 Boost 1.55.0。

【问题讨论】:

  • 缺乏对代码中所做工作的更完整视图,我建议您阅读参数相关查找

标签: c++ boost operator-overloading boost-log widestring


【解决方案1】:

我认为你不能用BOOST_LOG_TRIVIAL 做到这一点。 trivial logger 使用底层的boost::sources::logger 而不是boost::sources::wlogger,您可以从 boost 源文件中的 trivial.hpp 和 trivial.cpp 中看到,除非我们修改源代码,否则我无法看到如何更改它.如果您使用wlogger,它会起作用。这是一个例子:

#include <iostream>
#include <string>
#include <boost/log/sources/logger.hpp>
#include <boost/log/common.hpp>

namespace src = boost::log::sources;

class CWindowClassId
{
public:
    // ...
    friend std::wostream& operator<< (std::wostream& os, CWindowClassId const& classId)
    {
        os << classId.ws;
        return os;
    }
public:
    std::wstring ws;
};

int main(int argc, char* argv[])
{
    src::wlogger lg;
    CWindowClassId id;
    id.ws = L"wide char";
    BOOST_LOG(lg) << "Hello, World! This is a wide character message."<<id;
    return 0;
}

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 2012-08-10
    • 2015-01-12
    • 1970-01-01
    相关资源
    最近更新 更多