简体   繁体   English

C++ 使用 operator<< 输出作为函数中的参数

[英]C++ use operator<< output as parameter in function

I'm new to c++.我是 C++ 的新手。 I've seen a bazillion examples of the use of the operator<< where the output is sent to cout or cerr .我已经看到了无数使用operator<<示例,其中将输出发送到coutcerr Most classes overload this operator to have a human readable output in console, for instance in this example :大多数类重载此运算符以在控制台中具有人类可读的输出,例如在此示例中

ostream& operator<<(ostream& os, const Date& dt)
{
    os << dt.mo << '/' << dt.da << '/' << dt.yr;
    return os;
}

It allows to do this:它允许这样做:

Date dt(5, 6, 92);
cout << "The date is " << dt;

Now, I want to do the same thing, but I want to output to a file, not to a console.现在,我想做同样的事情,但我想输出到文件,而不是控制台。 I'm using Boost, and I'm following the example here :我正在使用 Boost,我正在按照此处的示例进行操作

logging::record rec = lg.open_record();
if (rec)
{
    logging::record_ostream strm(rec);
    strm << "Hello, World!";
    strm.flush();
    lg.push_record(boost::move(rec));
}

The example is fine, but I want to put this code into a function.这个例子很好,但我想把这段代码放到一个函数中。 This is my code so far:到目前为止,这是我的代码:

namespace logging = boost::log;

void log(severity_level level, std::string message)
{
    src::severity_logger<severity_level> lg;
    logging::record rec = lg.open_record(keywords::severity = level);
    if (rec)
    {
        logging::record_ostream strm(rec);
        strm << message;
        strm.flush();
        lg.push_record(boost::move(rec));
    }
}

Of course this works for string , but it won't work with the Date from the example above:当然这适用于string ,但它不适用于上面示例中的Date

Date dt(5, 6, 92);
log(severity_level::info, "The date is "); // No problem here
log(severity_level::info, dt); // Error, dt is not of type string

How can I do something like that?我怎么能做这样的事情?

To support multiple types, make log() a template function.要支持多种类型,请将log()设为模板函数。 Problem with your original code is that you only overloaded operator<< , and you have not overloaded any conversion operators .原始代码的问题在于您只重载了operator<< ,而没有重载任何转换运算符

template<typename T>
void log(severity_level level, const T& message)
{
    // ...
    strm << message;
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM