Operator overloading and namespaces

Viewed 10679

Possible Duplicate:
Where should non-member operator overloads be placed?

While browsing on SO, I often find questions or answer that involves overloading/defining a std::ostream& operator<<(std::ostream& os, const Foo& foo) or a Foo operator+(const Foo& l, const Foo& r).

While I know how and when (not) to write these operators, I'm confused about the namespace thing.

If I have the following class:

namespace bar
{
  class Foo {};
}

In which namespace should I write the different operator definitions ?

// Should it be this

namespace bar
{
  std::ostream& operator<<(std::ostream& os, const Foo& foo);
}

// Or this ?

namespace std
{
  ostream& operator<<(ostream& os, const bar::Foo& foo);
}

// Or this ?

std::ostream& operator<<(std::ostream& os, const bar::Foo& foo);

The same question applies for the operator+. So, what is the good practice here and why ?

5 Answers
Related