Missing javascript, are we?
Here's one way:
Code:
struct variable
{
enum var_type
{
unassigned,
string_type,
double_type
};
var_type type;
string string_rep;
double double_rep;
variable & operator += (const char * str)
{
if(type == unassigned)
type = string_type;
if(type == string_type)
{
string_rep += str;
}
else if(type == double_type)
{
double_rep += strtod(str, 0);
}
return *this;
}
variable & operator += (double val)
{
if(type == unassigned)
type = double_type;
if(type == string_type)
{
char str[16];
sprintf(str, "%f", val);
string_rep += str;
}
else if(type == double_type)
{
double_rep += val;
}
return *this;
}
variable & operator = (const char * str)
{
if(type == unassigned)
type = string_type;
if(type == string_type)
{
string_rep = str;
}
else if(type == double_type)
{
double_rep = strtod(str, 0);
}
return *this;
}
variable & operator = (double val)
{
if(type == unassigned)
type = double_type;
if(type == string_type)
{
char str[16];
sprintf(str, "%f", val);
string_rep = str;
}
else if(type == double_type)
{
double_rep = val;
}
return *this;
}
variable & operator += (variable & val)
{
if(val.type == string_type)
{
return *this += val.string_rep.c_str();
}
else if(val.type == double_type)
{
return *this += val.double_rep;
}
return *this;
}
variable & operator = (variable & val)
{
if(val.type == string_type)
{
return *this = val.string_rep.c_str();
}
else if(val.type == double_type)
{
return *this = val.double_rep;
}
return *this;
}
variable(const char * str)
:type(string_type)
{
*this = str;
}
variable(double val)
:type(double_type)
{
*this = val;
}
variable()
:type(unassigned), double_rep(0), string_rep("")
{
}
friend ostream & operator << (ostream & out, variable & _this)
{
if(_this.type == variable::string_type)
{
out << _this.string_rep;
}
else if(_this.type == variable::double_type)
{
out << _this.double_rep;
}
return out;
}
friend istream & operator >> (istream & in, variable & _this)
{
if(_this.type == variable::string_type)
{
in >> _this.string_rep;
}
else if(_this.type == variable::double_type)
{
in >> _this.double_rep;
}
return in;
}
};
Code:
int main()
{
variable str = "This is ";
variable num = 1;
str += num;
str += " way to do it!";
cout << str << endl;
str = "255";
num += str;
cout << num << endl;
cin.get();
}