How does the operator overload resolution work within namespaces?

前端 未结 3 1922
闹比i
闹比i 2020-12-29 10:56

I found a strange behaviour of C++ resolution of operator-overloading, I can\'t explain myself. A pointer to some resource describing it would be just as nice as an answer.<

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 11:55

    This is a name hiding issue. The standard says (c++03, 3.3.7/1)

    A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2).

    The "name" on your case would be operator>> and namespaces constitute nested declarative regions.

    The easiest way to fix that would be to use a using declaration where you declare the namespace-local operator<<:

    namespace your_namespece {
        std::istream& operator>>(std::istream& is, SomeClass& obj) { return is; }; 
        using ::operator>>;
    }
    

    Note that this feature doesn't interfere with Koenig lookup (at least in your case, in principle, it can), so IO operators from std:: will still be found.

    PS: Another possibility for working aroud this issue would be defining the operator for SomeClass as an inline friend. Such functions are declared at the namespace level (outside of "their" class), but are not visible from there. They can only be found by Koenig lookup.

提交回复
热议问题