[英]ADL using std types fails to find operator
以下代码无法编译
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名称空间中的类,因此找不到<< <<运算符。 有什么方法可以确保编译器找到此运算符或以其他方式解决该问题?
A::C
只是类型别名,别名是透明的。 他们不会“记住”他们来自哪里。 当我们进行依赖于参数的查找并弄清楚关联的名称空间是什么时,我们仅考虑类型的关联名称空间-而不是使我们到达那里的别名。 您不能只是将关联的名称空间添加到现有类型。 f
的特定关联命名空间(类型为std::vector<std::string>
)为std
,没有与之关联的operator<<
。 由于没有使用普通查询找到的operator<<
,也没有使用ADL找到的operator<<
,因此调用失败。
现在,我说过不能将关联的名称空间添加到现有类型中。 但是,您当然可以创建新类型:
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>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.