I have a class with lots of member data. I want to be able to define a function that I pass in which member in the class I want the function to operate on (read and write to that member of different instantiated class variables). I was able to find a solution that works (getting the address of the specific member variable relative to the class and passing it in to the function), but it's not elegant. Are there any more elegant solutions (maybe using recent versions of c++)?
#include <QString>
#include <QList>
struct data //imagine this class has many more items, all named
{
int i1;
int i2;
double d1;
QString s1;
int i3;
QString s2;
double d2;
double d3;
int i4;
int i5;
QString s3;
QString s4;
};
struct data a, b, c;
QList<struct data> test;
//addrDiff specifies which member variable the function will work on
void doSomethingWithIntInData(int addrDiff, struct data *d, struct data *e)
{
int val1=*((int *)((long)d+(long)addrDiff));
*((int *)((long)e+(long)addrDiff))=44;
//... do a bunch of stuff
}
int main(void)
{
test.append(c);
test[0].i4=43;
b.i4=42;
doSomethingWithIntInData(((char *)&a.i4-(char *)&a), &b, &test[0]);
}
A pointer to a member variable works well for this. If you change the function to something like
void doSomethingWithIntInData(data& d, int data::*var)
{
std::cout << d.*var << "\n";
}
Then you can tell the function which integer member to use when you call the function like
doSomethingWithIntInData(data_object, &data::int_member_name);
You can see this working in this live example.