Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload operator << Boost Log

Tags:

c++

c++11

stl

boost

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;

Hello,

I overloaded my operator<< for a std::vector. When i use std::cout it works well, but with boost log i get following error:

boost/log/utility/formatting_ostream.hpp:710:19: error: cannot bind 'boost::log::v2_mt_posix::basic_formatting_ostream::ostream_type {aka std::basic_ostream}' lvalue to 'std::basic_ostream&&' strm.stream() << value;

/opt/gcc.4.9.1/include/c++/4.9.1/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits; _Tp = std::vector]' operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

I have no idea why boost log is not working. It uses the same << operator or? On other examples with own classes it works well with overloading. I have no idea what I miss. Anyone has an idea how i can solve this error?

like image 782
Hunk Avatar asked Oct 02 '14 07:10

Hunk


1 Answers

'boost::log::basic_formatting_ostream is not derived from std::ostream.

You should overload operator << for std::vector and the overloaded operator should take boost::log::formatting_ostream& as its first parameter.

Check the modified code example below:

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;
}
like image 196
Nipun Talukdar Avatar answered Oct 24 '22 02:10

Nipun Talukdar