I need to make use of a C++'s pointer-to-member feature to make a function access a member of a substructure. Note that the object the function must operate on is not visible to the caller.
I have reduced it to the following toy problem (C++14 or later):
#include <iostream>
struct SubStruct {
int c;
};
struct MyStruct {
int a;
int b;
float f;
SubStruct ss;
};
template <typename Tmember>
auto addTogether(Tmember member) {
MyStruct s1 = {.a = 1, .b =2, .f =3.3, .ss = {.c = 4}};
MyStruct s2 = {.a = 10, .b =20, .f =30.0, .ss = {.c = 40}};;
return s1.*(member) + s2.*(member);
}
int main() {
std::cout << "sum a = " << addTogether(&MyStruct::a) << std::endl;
std::cout << "sum b = " << addTogether(&MyStruct::b) << std::endl;
std::cout << "sum f = " << addTogether(&MyStruct::f) << std::endl;
//std::cout << "sum c = " << addTogether(&MyStruct::ss::c) << std::endl; //DOES NOT WORK
//std::cout << "sum c = " << addTogether(&MyStruct::ss.c) << std::endl; //DOES NOT WORK
return 0;
}
The output is as expected:
sum a = 11
sum b = 22
sum f = 33.3
But how do I pass in the pointer to the data member ss.c ? See the two commented out lines in main().
Thanks.