从 C++ 中的父命名空间访问隐藏运算符
Accessing hidden operator from parent namespace in C++
我想拦截命名空间内的运算符 <<,以便在打印出基本类型之前为它们添加一些额外的格式。这能做到吗?
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)
,因为 the corresponding operator<<
是一个成员函数。
但是,对于 operator<<
,您将无法再在命名空间 Foo 中使用 std::cout << true
等表达式,因为这会导致 Foo::operator<<(std::ostream&, bool)
和 std::ostream
的成员函数std::ostream::operator<<(bool)
:都接受std::ostream
类型的左值作为左操作数,都接受bool
类型的值作为右操作数,哪一个都更好比另一个。
我想拦截命名空间内的运算符 <<,以便在打印出基本类型之前为它们添加一些额外的格式。这能做到吗?
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)
,因为 the corresponding operator<<
是一个成员函数。
但是,对于 operator<<
,您将无法再在命名空间 Foo 中使用 std::cout << true
等表达式,因为这会导致 Foo::operator<<(std::ostream&, bool)
和 std::ostream
的成员函数std::ostream::operator<<(bool)
:都接受std::ostream
类型的左值作为左操作数,都接受bool
类型的值作为右操作数,哪一个都更好比另一个。