c++ - operator << argument-dependent lookup 不在全局命名空间中查找

标签 c++ namespaces operator-overloading argument-dependent-lookup

在以下场景中,在 function() 内部,行 ss << bb ,我得到一个错误:

binary '<<': no operator found which takes a right-hand operand of type 'CommonType' (or there is no acceptable conversion) error.

我对 ADL 的理解是它将查看当前命名空间(即 AppNamespace::InnerNamespace )并且因为没有 operator <<找到后,它将查看参数的命名空间并作为 CommonType在全局命名空间中我希望 operator <<定义在CommonTypes.h 中可以找到。 显然我的理解是错误的。谁能弄清楚这应该如何工作?

main.cpp

namespace AppNamespace
{

    typedef std::vector<std::string> OtherType;

    std::ostream& operator << (std::ostream& os, const OtherType& ot)
    {
        for (auto& el : ot)
        {
            os << el;
        }
        return os;
    }

    namespace InnerNamespace
    {
        void function()
        {
            CommonType bb;
            std::stringstream ss;
            ss << bb;
        }
    }
}


int main()
{
    AppNamespace::InnerNamespace::function();
    return 0;
}

CommonTypes.h:

    #pragma once

#include <vector>

typedef std::vector<uint8_t> CommonType;

std::ostream& operator << (std::ostream& os, const CommonType& bb)
{
        for (auto& el : bb)
        {
            os << el;
        }
        return os;
}

最佳答案

这里的问题是 ADL 查找将在 std 命名空间和声明 CommonType 的命名空间中执行是不相关的,所以为了使这项工作你需要将运算符 << 放在适当的命名空间中:

namespace std
{

ostream& operator << (ostream& os, const CommonType& bb)
{
    for (auto& el : bb)
    {
        os << el;
    }
    return os;
}

}

关于c++ - operator << argument-dependent lookup 不在全局命名空间中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50257432/

相关文章:

php - 为什么在 PHP 中使用 "use"关键字来导入核心标识符?

c# - C# 中的 Tribool 实现

c++ - 为二叉树重载++ 运算符

c++ - 快速 C++ I/O 将字符串(字符数组)读入 vector ,并解决错误

c++ - 从 C++ 调用 Lua 函数,缺少参数

c++ - 灵气中如何将迭代器传给函数

vb.net - 不使用类的命名空间来声明对象

.net - 首选命名空间命名约定

c++ - 类对象到字符串的隐式转换运算符

c++ - Windows 上的 CMake 和 MinGW 编译,无需 -G "MinGW Makefiles"标志