Overloading operators in namespaces

Words
78
Reading
1 min
Listen
Play
5y

It's very common to overload operators for custom C++ classes but sometimes the overloaded operator is not actually used, if the class is defined in different namespace as the overloaded operator.

To fix this, the overloaded operator must be moved to same namespace as the class is defined and where the operator is used, this allows using just the class name and not fully qualified name that includes all the namespaces the class is defined in.

Incorrect:

namespace {

std::ostream& operator<<(std::ostream& os, const CryptoNote::IBlockchainConsumer* consumer) {
  return os << "0x" << std::setw(8) << std::setfill('0') << std::hex << reinterpret_cast<uintptr_t>(consumer) << std::dec << std::setfill(' ');
}

}

Correct:

namespace CryptoNote {

std::ostream& operator<<(std::ostream& os, const IBlockchainConsumer* consumer) {
  return os << "0x" << std::setw(8) << std::setfill('0') << std::hex << reinterpret_cast<uintptr_t>(consumer) << std::dec << std::setfill(' ');
}

}
Overloading operators in namespaces | Ecency