[英]ADL using std types fails to find operator
The following code fails to compile 以下代码无法编译
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;
}
with the error 与错误
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'A::C' (or there is no acceptable conversion)
Obviously it cant find the << operator presumably due to considering C to be a class from the std namespace. 显然,由于将C视为std名称空间中的类,因此找不到<< <<运算符。 Is there some way to ensure the compiler finds this operator or otherwise work around the problem? 有什么方法可以确保编译器找到此运算符或以其他方式解决该问题?
A::C
is just a type alias, and aliases are transparent. A::C
只是类型别名,别名是透明的。 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. f
的特定关联命名空间(类型为std::vector<std::string>
)为std
,没有与之关联的operator<<
。 Since there's no operator<<
found using ordinary lookup, nor is there one found using ADL, the call fails. 由于没有使用普通查询找到的operator<<
,也没有使用ADL找到的operator<<
,因此调用失败。
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>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.