在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)
,因为对应的operator<<
是一个成员函数。
但是,对于您的operator<<
,您将不再能够在名称空间Foo中使用std::cout << true
这样的表达式,因为这会引发Foo::operator<<(std::ostream&, bool)
和std::ostream
的成员函数std::ostream::operator<<(bool)
之间的歧义:它们都接受std::ostream
类型的左值作为其左操作数,都接受bool
类型的值作为其右操作数,两者都不如。
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 使用TDD时隐藏文件访问实现详细信息
- 在C 中本地声明隐藏的封闭范围(而非全局)中访问变量
- 隐藏的成员变量不应在仅允许const访问的基类中突变,以便保留分配运算符
- 如何在不授予私有成员访问权限的情况下隐藏 C++ 中的 STL 函子结构
- 如何在C++中隐藏我的AWS S3访问密钥和秘密
- 访问具有不同签名的基类中的隐藏函数
- 如何处理基类函数已经重载不同访问权限时的名称隐藏问题
- 名称隐藏和访问基类的非虚函数(语法)
- 多态性和数据隐藏:基类是覆盖还是忽略派生类的访问限制?
- 访问隐藏的继承成员
- 在g++中我可以访问哪些其他隐藏变量(使用宏预先定义的)?
- 在c++中从父命名空间访问隐藏操作符