【问题标题】:Accessing hidden operator from parent namespace in C++从 C++ 中的父命名空间访问隐藏运算符
【发布时间】:2015-07-17 05:26:58
【问题描述】:

我想在命名空间中截获运算符

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

谢谢!

【问题讨论】:

标签: c++ operators


【解决方案1】:

您可以使用显式的函数调用语法来做到这一点。对于您的情况,调用应该是os.operator&lt;&lt;(b ? 10 : -10),因为the corresponding operator&lt;&lt; 是一个成员函数。

但是,使用您的operator&lt;&lt;,您将无法再在命名空间 Foo 中使用诸如 std::cout &lt;&lt; true 之类的表达式,因为这将触发您的 Foo::operator&lt;&lt;(std::ostream&amp;, bool) 和 std::ostream 的成员函数 @987654328 之间的歧义@: 都接受std::ostream 类型的左值作为其左操作数,并且都接受bool 类型的值作为其右操作数,两者都不比另一个更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多