Mika avatar

Overloading operators in namespaces

mtl1979

Published: 28 Mar 2022 › Updated: 28 Mar 2022Overloading operators in namespaces

Overloading operators in namespaces

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(' ');
}

}

Leave Overloading operators in namespaces to:

Written by

Freelance journalist, software designer

Read more #development posts


Best Posts From Mika

We have not curated any of mtl1979's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Mika