ADL using std types fails to find operator

后端 未结 1 438
野性不改
野性不改 2020-12-11 03:24

The following code fails to compile

namespace A {
using C = std::vector;
std::ostream& operator << (std::ostream& lhs, cons         


        
相关标签:
1条回答
  • 2020-12-11 04:13

    A::C is just a type alias, and aliases are transparent. They don't "remember" where they came from. When we do argument-dependent lookup and figure out what the associated namespaces are, we only consider the associated namespaces of the types - not the alias that got us there. You can't just add associated namespaces to existing types. The specific associated namespace of f (which is of type std::vector<std::string>) is std, which doesn't have an operator<< associated with it. Since there's no operator<< found using ordinary lookup, nor is there one found using ADL, the call fails.

    Now, I said you can't just add associated namespaces to existing types. But you can of course just create new types:

    namespace A {
        struct C : std::vector<std::string> { };
    }
    

    or:

    namespace A {
        // template parameters are also considered for associated namespaces
        struct S : std::string { };
        using C = std::vector<S>;
    }
    
    0 讨论(0)
提交回复
热议问题