[英]Printing std::vector of a user defined type
Please, look at the two code chunks below. 请看下面的两个代码块。 In the second one I've just put the class A into a namespace. 在第二个我刚刚将类A放入命名空间。 And now my mind boiled up trying to understand why the first one chunk is ok and the second one chunk is not. 而现在我的脑海里浮现出来试图理解为什么第一个块是好的而第二个块不是。 Sorry, for a mostly code. 对不起,主要是代码。 Could you explain me why? 你能解释一下为什么吗? I used Microsoft compiler C++14. 我使用的是Microsoft编译器C ++ 14。 Please, help. 请帮忙。
This is ok: 还行吧:
#include <iostream>
#include <vector>
#include <iterator>
class A;
class A{};
std::ostream & operator<<(std::ostream & out, const A & a)
{
out << "A";
return out;
}
int main()
{
std::vector<A> v({ A(), A(), A() });
//Prints: "A A A "
std::copy(v.begin(), v.end(), std::ostream_iterator<A>(std::cout, " "));
return 0;
}
This is not ok: 这不行:
#include <iostream>
#include <vector>
#include <iterator>
namespace N { class A; }
class N::A{};
std::ostream & operator<<(std::ostream & out, const N::A & a)
{
out << "A";
return out;
}
int main()
{
std::vector<N::A> v({ N::A(), N::A(), N::A() });
//Compiler error C2679:
std::copy(v.begin(), v.end(),
std::ostream_iterator<N::A>(std::cout, " "));
//But this is still ok and prints "A A A" as intended.
//Please, uncomment and try:
/*
for (std::vector<N::A>::iterator it = v.begin(); it != v.end(); ++it)
std::cout << *it << " ";
*/
return 0;
}
The issue is std::copy
can't find operator<<
, without the help of ADL . 问题是std::copy
找不到operator<<
,没有ADL的帮助。 It knows nothing about operator<<
defined by you. 它对您定义的operator<<
一无所知。
So you need to move operator<<
into the same namespace where class A
declared, to make ADL to take effect, then operator<<
could be found. 因此,您需要将operator<<
移动到A
类声明的同一名称空间中,以使ADL生效,然后可以找到operator<<
。
namespace N {
class A;
std::ostream & operator<<(std::ostream & out, const A & a);
}
class N::A{};
std::ostream & N::operator<<(std::ostream & out, const N::A & a)
{
out << "A";
return out;
}
Note for the first case, it works well, still because of ADL. 注意第一种情况,它运行良好,仍然是因为ADL。 Just the namesapce is global namespace (where class A
and operator<<
defined). 只有namesapce是全局命名空间(其中A
类和operator<<
定义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.