Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload operator<< in google c++ style

Tags:

c++

I try to overload operator<< for my class so that it print member when I do std::cout << obj;

I see that the way to do this is

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // write obj to stream

  return os;
}

What are the basic rules and idioms for operator overloading?

However, I try to make my code conforms to Google C++ style guide https://google.github.io/styleguide/cppguide.html#Reference_Arguments

It says that passing the reference without const is not allowed except for the case that it is needed by convention such as swap(). Is this overloading operator<< in the same category as swap()? or there is a way to do something like

std::ostream& operator<<(std::ostream* os, const T& obj)
                                     ^

? or something that does not take non-const reference as the input.

If so, please teach me how to do that. Thank you.

like image 470
EKP Avatar asked Oct 10 '18 15:10

EKP


1 Answers

It says that passing the reference without const is not allowed except for the case that it is needed by convention

Well, the stream is conventionally passed as a non-const reference into the stream insertion and extraction operators, so it would appear that the rule has allowed an exception for you. As such, defining the suggested overload should be conforming to the rule despite accepting a non-const reference argument.

That said, I'm not an authority on what Google would consider as convention. If you work for Google, you should know whom to ask; If you don't then you don't need to get stressed over their style.

like image 126
eerorika Avatar answered Nov 17 '22 00:11

eerorika