问题描述
我在尝试做一些像
std::cout << std::vector<int>{1,2,3};
说的是
cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
int main() { std::cout << std::vector<int>{1,2,3}; }
(使用 gcc-4.8.1 和 -std=c++11 测试)
(tested using gcc-4.8.1 with -std=c++11)
SO 有类似的问题,例如 重载运算符<,它是关于一些用户定义的带有嵌套类的类.还有一个解决该问题的公认答案的工作.
但我不知道这是否适用于 std::vector
.有人可以解释为什么 std::vector
会发生这个错误,以及如何解释它?
推荐答案
如果要流式传输整个容器,可以使用 std::ostream_iterator
为此:
If you want to stream an entire container, you can use std::ostream_iterator
for that:
auto v = std::vector<int>{1, 2, 3};
std::copy(begin(v), end(v), std::ostream_iterator<int>(std::cout, " "));
至于为什么你会得到这个神秘的错误,它有助于分析完整的错误消息:
As for why you're getting precisely this cryptic error, it helps to analyse the full error message:
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&&
.因此出现错误.
There is apparently a template overload of operator<<
which takes a lhs argument of type std::ostream&&
and a rhs argument of the templated type; it exists to allow insertion into temporary streams. Since it's a template, it becomes the best match for the expression in your code. However, std::cout
is an lvalue, so it cannot bind to std::ostream&&
. Hence the error.
这篇关于std::vector :无法将“std::ostream {aka std::basic_ostream<char>}"左值绑定到“std::basic_ostream<char>&&"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!