I know you can overload functions but is there a way to pass any type variable to a function and then tell it's size within the function?
For example, say I wanted to be able to store any variable in EEPROM, can I have a function that will store any size variable?
I think they use void pointers for that very reason.. However!!! If the eeprom has to cater for all sizes, then the biggest size will need to be reserved.. so cast ANY size to a 64bit long long and store that..
I normally create a union for this case.. 4 bytes, two int's and a long.. Once you recieve the data ( via a void pointer ) you can try sizeof() to see if it returns the correct amount of bytes.. Then place it into the union..
For such as EEPROM reading or writing, I just pass the data size (or count) as well as a pointer to the data start & eeprom address..
No extra variables, nothing reserved etc.
Or if you wanted a single variable, put all that in a struct{} and pass a pointer to the structure.
One way to do this in c++ would be to derive all types you want to pass from one base class, e.g. MyObject
Code:
enum { OBJECT1 = 1, OBJECT2 = 2};
class MyObject
{
public:
virtual int Type() = 0;
};
class Object1 : public MyObject
{
public:
virtual int Type() {return OBJECT1;}
};
class Object2 : public MyObject
{
public:
virtual int Type() {return OBJECT2;}
};
Then you can use them like:
Code:
....
Object1 obj1;
Object2 obj2;
DoSomething(&obj1);
DoSomething(&obj2);
..
void DoSomething(MyObject* pObj)
{
switch (pObj->Type())
{
case OBJECT1:
{
unsigned int size = sizeof(Object1);
Object1* p = (Object1*)pObj;
.....
break;
}
case OBJECT2:
.....
break;
default:
assert(false);
}
}
If all you are interested in is the size, you could add a virtual function to the base class which returns the size of the object, and simply overload it for each derived class.
Alternatively, if this suits your application, you could tell each derived class how to store itself, and simply have:
Code:
class MyObject
{
public:
virtual int Type() = 0;
virtual void Store() = 0;
};
class Object1 : public MyObject
{
public:
virtual int Type() {return OBJECT1;}
virtual void Store() {code to store this object, probably in cpp file}
};
class Object2 : public MyObject
{
public:
virtual int Type() {return OBJECT2;}
virtual void Store() {code to store this object, probably in cpp file}
};
....
Object1 obj1;
Object2 obj2;
...
obj1.Store();
obj2.Store();