与模板相关的错误消息有时会令人困惑。问题是标准库没有定义operator << 的重载以将std::vector(或任何其他容器,就此而言)插入std::ostream。因此,编译器无法为 operator << 找到合适的重载,并尽其所能报告此失败(不幸的是,在您的情况下这不太好/可读)。
如果你想流式传输整个容器,你可以使用std::ostream_iterator:
auto v = std::vector<int>{1, 2, 3};
std::copy(begin(v), end(v), std::ostream_iterator<int>(std::cout, " "));
至于为什么你会得到这个神秘的错误,它有助于分析完整的错误信息:
prog.cpp: In function ‘int main()’:
prog.cpp:13:37: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
std::cout << std::vector<int>{1,2,3};
^
In file included from /usr/include/c++/4.8/iostream:39:0,
from prog.cpp:3:
/usr/include/c++/4.8/ostream:602:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::vector<int>]’
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
^
显然存在operator<< 的模板重载,它采用std::ostream&& 类型的lhs 参数和模板类型的rhs 参数;它的存在是为了允许插入到临时流中。由于它是一个模板,因此它成为代码中表达式的最佳匹配。但是,std::cout 是一个左值,所以它不能绑定到std::ostream&&。因此出现错误。