【问题标题】:C++ use operator<< output as parameter in functionC++ 使用 operator<< 输出作为函数中的参数
【发布时间】:2020-09-09 08:42:46
【问题描述】:

我是 C++ 新手。我见过无数使用operator&lt;&lt; 的示例,其中输出发送到coutcerr。大多数类重载此运算符以在控制台中获得人类可读的输出,例如in this example

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

它允许这样做:

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

现在,我想做同样的事情,但我想输出到文件,而不是控制台。我正在使用 Boost,我正在关注the example here

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

这个例子很好,但我想把这段代码放到一个函数中。到目前为止,这是我的代码:

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));
    }
}

当然这适用于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

我该怎么做?

【问题讨论】:

  • " 它不适用于上面的 Date 示例" - 为什么不呢? logging::record_ostream 不是派生自 std::ostream&amp; 吗?否则我看不出有什么明显的原因导致它不起作用
  • 您标记了boost,所以我想logging::record_ostream 来自boost?您可能需要另一个重载来接受提升流。
  • @UnholySheep 因为我正在记录message,我在最后一段代码中将其作为字符串参数传递。对不起,如果问题不清楚,我会编辑。
  • @Yksisarvinen 它是namespace logging = boost::log;, as defined here in the docs;固定。

标签: c++ boost operator-keyword


【解决方案1】:

要支持多种类型,请将log() 设为模板函数。你的原始代码的问题是你只重载了operator&lt;&lt;,而你没有重载任何conversion operators

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

【讨论】:

  • 谢谢,但它仍然不适合我。它正在编译,但随后我在 .o 文件中收到错误“未定义对 [function] 的引用”,好像链接器找不到模板函数一样。
  • 另外,我不明白在我的情况下我应该如何处理转换运算符...
  • @ocramot 如果要将Date 隐式转换为std::string,请为其创建operator std::string()
猜你喜欢
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 2013-11-09
  • 2022-11-21
  • 2021-10-23
  • 2013-06-24
  • 1970-01-01
  • 2011-09-14
相关资源
最近更新 更多