【问题标题】:overload operator << Boost Log重载运算符 << Boost Log
【发布时间】:2014-11-27 03:36:51
【问题描述】:
inline std::ostream& operator<<(std::ostream& p, const std::vector<unsigned int>& vector){
  p << "[ ";
  for(auto i:vector){
    p << " "<< i << " ,";
  }
  p<< "]";
  return p;
}

#define LOG_DEBUG_MESSAGE BOOST_LOG_SEV(my_logger::get(), debug)


std::vector<unsigned int> test {1, 2, 3};
LOG_DEBUG_MESSAGE << "test "<< test;
std::cout << test  << std::endl;

你好,

我为 std::vector 重载了运算符

boost/log/utility/formatting_ostream.hpp:710:19:错误:无法绑定 'boost::log::v2_mt_posix::basic_formatting_ostream::ostream_type {aka std::basic_ostream}' 左值到 'std::basic_ostream&&' strm.stream()

/opt/gcc.4.9.1/include/c++/4.9.1/ostream:602:5:注意:正在初始化 'std::basic_ostream<_chart _traits>& 的参数 1 std::operator&&, const _Tp&) [与_CharT = char; _Traits = std::char_traits; _Tp = 标准::向量]' 运算符&& __os, const _Tp& __x)

我不知道为什么 boost 日志不起作用。它使用相同的

【问题讨论】:

  • Boost 日志使用重载的输出运算符,但它可能在另一个类类型上重载,而不是 std::ostream,这就是您的代码不起作用的原因。
  • 作为一个实验,能否尝试在std命名空间中定义这个&lt;&lt;操作符,并确认它是否可以编译?
  • 也许你的特质类型不匹配?尝试将operator&lt;&lt; 定义为模板template&lt;typename CharT, typename Traits&gt; inline std::basic_ostream&lt;CharT, Traits&gt;&amp; operator&lt;&lt;(std::basic_ostream&lt;CharT, Traits&gt;&amp; p, //etc
  • bobah 是正确的,如果您在命名空间中定义函数,那么一切正常。 namespace std { signature here; }std::ostream&amp; std::operator&lt;&lt;() {}

标签: c++ c++11 boost stl


【解决方案1】:

'boost::log::basic_formatting_ostream 不是从 std::ostream 派生的。

你应该为 std::vector 重载操作符

查看下面修改后的代码示例:

inline boost::log::formatting_ostream& operator<<(boost::log::formatting_ostream& p,  std::vector<int>& vector)
{
        p << "[ ";
        for(auto i:vector){
            p << " "<< i << " ,";
        }
        p<< "]";
        return p;
}

【讨论】:

  • 实际上你可以像其他帖子中提到的那样重载 std::ostream ,例如stackoverflow.com/questions/32902904/…
  • 但是,您需要在 与要重载的数据类型相同的命名空间中获取它,例如在 boost 的 point_xy 的情况下几何:namespace boost { namespace geometry { namespace model { namespace d2 { template&lt;typename CT, typename CS&gt; inline std::ostream &amp; operator&lt;&lt; (std::ostream &amp;os, point_xy&lt;CT, CS&gt; const &amp;pt) { os &lt;&lt; "[point_xy: " &lt;&lt; pt.x() &lt;&lt; ", " &lt;&lt; pt.y() &lt;&lt; "]"; return os; } }}}}
  • 如果你使用auto,那么也使用引用for (auto &amp;i : vector) {..}以避免在向量类型改变时复制
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
  • 1970-01-01
相关资源
最近更新 更多