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