MK.
MK.

Reputation: 4017

Accessing hidden operator from parent namespace in C++

I want to intercept the operator << inside a namespace to add some additional formatting to basic types before printing them out. Can this be done?

namespace Foo {
    std::ostream& operator<<(std::ostream& os, bool b) {
        //Can I call std::operator<< here now. Something like:
        // os std::<< (b ? 10 : -10) << std::endl;
    }
}

Thanks!

Upvotes: 1

Views: 121

Answers (1)

cpplearner
cpplearner

Reputation: 15813

You can do it using explicit function call syntax. For your case, the call should be os.operator<<(b ? 10 : -10), because the corresponding operator<< is a member function.

However, with your operator<<, you will no longer be able to use expressions such as std::cout << true in namespace Foo, because this will trigger an ambiguity between your Foo::operator<<(std::ostream&, bool) and std::ostream's member function std::ostream::operator<<(bool): both accept an lvalue of type std::ostream as its left operand, and both accept a value of type bool as its right operand, neither is better than the other.

Upvotes: 1

Related Questions