gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:33:56 28 4
gpt4 key购买 nike

在以下场景中,在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com