我尝试以下代码:
ostringstream oss;
streambuf *psbuf, *backup;
backup = oss.rdbuf();
psbuf = cout.rdbuf();
oss.rdbuf(psbuf);
oss << things << endl;
oss.rdbuf(backup);
Run Code Online (Sandbox Code Playgroud)
但是不幸的是我得到了这个错误:
error: too many arguments to function call, expected 0, have 1
oss.rdbuf(backup);
Run Code Online (Sandbox Code Playgroud)
但是rdbuf有两个重载:
得到(1)basic_streambuf <char_type,traits_type> * rdbuf()const;
设置(2)basic_streambuf <char_type,traits_type> * rdbuf(basic_streambuf <char_type,traits_type> * sb);
是的,我知道它说,basic_streambuf但是它实际上只是一个typedef typedef basic_streambuf<char> streambuf;,因此它应该可以工作。为什么不起作用?
我尝试使用以下代码推广流对象:
#include <iostream>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
template<class T, class U>
T& operator<<(T& os, vector<U> vec)
{
vector<string>::iterator begin = vec.begin();
vector<string>::iterator end = vec.end();
for (; begin != end; ++begin)
os << *begin << " ";
return os;
}
int main()
{
vector<string> things({
"car", "truck", "rabbit"
});
ostringstream oss;
oss << things << endl;
copy(oss.str().begin(), oss.str().end(), ostream_iterator<char>(cout, ""));
}
Run Code Online (Sandbox Code Playgroud)
现在,它与工作cout << things和string str = oss.str(); copy(str.begin() ...,但不与oss.str().begin().据我所知, …