How does one go about passing a struct member identifier to a function such that the function can apply an operation to that specified member? The below code example should highlight what I am trying to achieve.
struct _struct {
int a = 0;
int b = 0;
};
_struct test[5];
void printVar(int index, ??? member) {
// Print specified member at array element
printf(test[index].member);
};
int operation(??? member) {
// Some operation applied to specified member of all array elements
// eg. Averaging all the readings contained in test[].a
int total = 0;
for (int i = 0; i < 5; i++) {
total += test.member;
};
return total / 5;
};
The closest I have found to a solution is described at the below link, whilst the principle is sound in its application it doesn't appear to be the best possible implementation. http://cplusplus.com/forum/beginner/45268/
std::maporstd::unordered_mapinstead of astruct, and then pass the desired key as the member identifier. Alternatively, you could pass astd::functionthat fetches the desired member from the an argument of type_struct.testand pass either memberaorbtooperation, so that it returns sum of allaorbfrom the array?