在c++中从父命名空间访问隐藏操作符

Accessing hidden operator from parent namespace in C++

本文关键字:访问 隐藏 操作符 命名空间 c++      更新时间:2023-10-16

我想截取运算符<<在将基本类型打印出来之前向它们添加一些额外的格式化。这能做到吗?

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;
    }
}

谢谢!

可以使用显式函数调用语法来实现。对于您的示例,调用应该是os.operator<<(b ? 10 : -10),因为对应的operator<<是一个成员函数。

但是,对于您的operator<<,您将不再能够在名称空间Foo中使用std::cout << true这样的表达式,因为这会引发Foo::operator<<(std::ostream&, bool)std::ostream的成员函数std::ostream::operator<<(bool)之间的歧义:它们都接受std::ostream类型的左值作为其左操作数,都接受bool类型的值作为其右操作数,两者都不如。