Basically I have to populate objects based on an input text file with the following syntax:
float 4.55 24 2.1
int 4 6 9 0
float 5.1 6 6
//char 255 3 5
And then I need to make some sort of operations on them (for example a simple adition) there is no way to know beforehand which types of data there will be.
I can't store them all internally as double variables because space optimitation is important as well as not loosing precision.
I thought of doing something like:
class Base {
public:
virtual size_t size() = 0;
virtual void addValue () = 0;
virtual void getValue (int index) = 0;
};
class BaseFloat : public Base{
public:
vector<float> data;
void addValue (float d);
float getValue (int index);
size_t size();
}
class BaseInt : public Base{
public:
vector<int> data;
void addValue (int d);
Int getValue (int index);
size_t size();
}
/* other classes for each data type here*/
This doesn't work as each function has diferent return types or parameter needs;
Then I have one class which creates the correct object for each line.
The problem comes when I need to have other class which should work with any type of Base. I was thinking something like:
class OtherClass {
public:
void addValue(Base*, double);
}
OtherClass my_class; //whatever
Base* a = new BaseFloat ();
Base* b = new BaseInt();
my_class.addData(a, 5.56); //Uses BaseFloat::addValue
my_class.addData(b, 6); //Uses BaseInt::addValue
my_class.addData(b, 6.55); //Uses BaseInt::addValue
I was hoping I could do this without adding some sort of long if-else clause like:
void OtherClass::addDataHelper (Base* pointer)
if (subclass(pointer) == float)
//Do BaseFloat* a = pointer;
//Do a->addValue
else if ...
Any ideas?
Aucun commentaire:
Enregistrer un commentaire