代码之家  ›  专栏  ›  技术社区  ›  R2RT

为什么ADL在使用免费运算符时失败<<对于别名模板,但对于普通结构或相同名称空间[duplicate]

  •  0
  • R2RT  · 技术社区  · 7 年前

    以下代码无法编译

    namespace A {
    using C = std::vector<std::string>;
    std::ostream& operator << (std::ostream& lhs, const C& rhs) {
        lhs << 5;
        return lhs;
    }
    }
    int main()
    {
        A::C f;
        std::cout << f;
        return 0;
    }
    

    带着错误

    Error   C2679   binary '<<': no operator found which takes a right-hand operand of type 'A::C' (or there is no acceptable conversion)   
    

    显然,它找不到<&书信电报;运算符可能是因为将C视为std命名空间中的一个类。有没有办法确保编译器找到这个操作符,或者解决这个问题?

    0 回复  |  直到 9 年前
        1
  •  8
  •   Barry    9 年前

    A::C 只是一个类型别名,而别名是透明的。他们不“记得”他们来自哪里。当我们进行依赖于参数的查找并找出相关的命名空间是什么时,我们只考虑相关的命名空间。 类型 -不是我们的化名。不能只向现有类型添加关联的名称空间。的特定关联命名空间 f (这是一种 std::vector<std::string> )是吗 std ,它没有 operator<< 与之相关。既然没有 操作员<&书信电报; 使用普通查找找到,也没有使用ADL找到,调用失败。

    现在,我说过不能只向现有类型添加关联的名称空间。但你当然可以创建新的类型:

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

    或者:

    namespace A {
        // template parameters are also considered for associated namespaces
        struct S : std::string { };
        using C = std::vector<S>;
    }
    
    推荐文章