Try this.
There is no casting. There is no template. The class is set up for int and float.
I convert input int to a string. I convert input float to a string.
When the user uses the object as int, it converts itself to an int. The same object will convert itself to a float if you use it as a float.
Let me know what you think.
There is no casting. There is no template. The class is set up for int and float.
I convert input int to a string. I convert input float to a string.
When the user uses the object as int, it converts itself to an int. The same object will convert itself to a float if you use it as a float.
Let me know what you think.
Code:
#include <iostream>
#include <vector>
#include <sstream>
#include <string.h>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
class GenericData
{
string data;
string Convert(int arg);
string Convert(float arg);
public:
GenericData(int arg);
GenericData(float arg);
operator int();
operator float();
};
GenericData::GenericData(int arg)
{
data = this->Convert(arg);
}
GenericData::GenericData(float arg)
{
data = this->Convert(arg);
}
string GenericData::Convert(int arg)
{
ostringstream str;
str << arg;
return str.str();
}
string GenericData::Convert(float arg)
{
ostringstream str;
str << arg;
return str.str();
}
//Conversion operators
GenericData::operator int()
{
stringstream str(this->data);
int temp = 0;
str >> temp;
return temp;
}
GenericData::operator float()
{
stringstream str(this->data);
float temp = 0;
str >> temp;
return temp;
}
int main()
{
GenericData obj1(5); //an int
GenericData obj2(3.14159f); //a double
int value (obj1);
float valuef(obj2);
cout << value << endl;
}
Comment