You'll have to create a manipulator. You can either create a user defined manipulator by using the implementation defined smanip structure (in iomanip), or create a flag that'll enable your operator << to establish whether your string needs clearing. Something like -
Code:
#include <string>
#include <iostream>
using namespace std;
struct my_string
{
string s;
enum clear { not_clear = 0, to_clear = 1 };
//constructor
my_string(char* p){s=p;}
//Obtain unique index for flag
static long& my_clear_flag(std::ios_base& s)
{
//Ensure that calling clear is for the correct
//instance using static member xalloc
static int my_index = std::ios_base::xalloc();
return s.iword(my_index);
}
static clear get_clear(std::ios_base& s)
{
return (clear) my_clear_flag(s);
}
static void set_clear(std::ios_base& s)
{
my_clear_flag(s) = ~get_clear(s);
}
friend ostream& operator<<(ostream& os, my_string& m)
{
if(get_clear(os))
{
m.s="";
set_clear(os);
}
return os<<m.s;
}
void SetString(char* c)
{
s = c;
}
};
//the iostream manipulator
std::ostream& Clear(std::ostream& os)
{
my_string::set_clear(os);
return os;
}
int main()
{
my_string m("Joe");
cout << m << Clear << m;
m.SetString("Sixpack");
cout << m;
return 0;
}