Ответ 1
Это можно решить с помощью нового типа streambuf
(см. Стандартные IOStreams и локали С++: Расширенное руководство для программистов и Ссылка).
Вот эскиз того, как он может выглядеть:
#include <streambuf>
class existing_string_buf : public std::streambuf
{
public:
// Store a pointer to to_append.
explicit existing_string_buf(std::string &to_append);
virtual int_type overflow (int_type c) {
// Push here to the string to_append.
}
};
Как только вы подробно изложите здесь информацию, вы можете использовать его следующим образом:
#include <iostream>
std::string s;
// Create a streambuf of the string s
existing_string_buf b(s);
// Create an ostream with the streambuf
std::ostream o(&b);
Теперь вы просто пишете на o
, и результат должен появиться как добавленный к s
.
// This will append to s
o << 22;
Изменить
Как правильно отмечает @rustyx, для повышения производительности требуется переопределение xsputn
.
Полный пример
Следующие отпечатки 22
:
#include <streambuf>
#include <string>
#include <ostream>
#include <iostream>
class existing_string_buf : public std::streambuf
{
public:
// Somehow store a pointer to to_append.
explicit existing_string_buf(std::string &to_append) :
m_to_append(&to_append){}
virtual int_type overflow (int_type c) {
if (c != EOF) {
m_to_append->push_back(c);
}
return c;
}
virtual std::streamsize xsputn (const char* s, std::streamsize n) {
m_to_append->insert(m_to_append->end(), s, s + n);
return n;
}
private:
std::string *m_to_append;
};
int main()
{
std::string s;
existing_string_buf b(s);
std::ostream o(&b);
o << 22;
std::cout << s << std::endl;
}