0%

Passing member names to functions

While doing my labs, I need to write or modify similar codes over and over again (such as sorting objects or modifying their attributes’ values).

My problem is: Is there a solution to input the name of the member so that I can simply paste it it when I need it to process different classes or structs?

Luckily, I found two solutions. This one calls the function offsetof() to get the offset of the member. It works well when I use struct but shows warning when I use class. This one uses template but you have to know the name of member before compilation.

Here I put the code below:

offsetof() solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Test
{
int x;
int y;
};

void example(void *base, size_t offset)
{
int *adr;
adr = (int*)((char*)base + offset);
printf("%d\n", *adr);
}

int main(int argc, char **argv)
{
struct Test t;

t.x = 5;
t.y = 10;

example(&t, offsetof(struct Test, y));
}

template solution:

1
2
3
4
5
template <typename ObjType, typename MembType>
void myOutput(ObjType* obj, MembType memb)
{
std::cout << obj->*memb << std::endl;
}