I have the following code:
#include <iostream>
#include <string>
using namespace std;
struct foo_s {
string a;
string b;
string c;
};
void print_field(foo_s* foo, string foo_s::* field) {
cout << "field: " << field << " - " << foo->*field << endl;
}
int main() {
foo_s my_foo = {
"a",
"b",
"c",
};
print_field(&my_foo, &foo_s::a);
print_field(&my_foo, &foo_s::b);
print_field(&my_foo, &foo_s::c);
return 0;
}
Its output is:
field: 1 - a
field: 1 - b
field: 1 - c
I'm having a bit of trouble understanding the specifics of what's going on in the print_field()
function. Namely:
- What's the type of
field
? I imagine it'spointer-to-string-foo_s-member
- Why is the value of
field
always the same (1 in this case), yetfoo->*field
yields different results?
Mainly, I'm baffled at #2. I imagined field would be an "offset" from the start of the struct and foo->*field
would have been conceptually equivalent to something like
char* ptr = static_cast<char*>(foo);
ptrdiff_t offset = somehow_get_the_byte_offset_from_pointer_to_member(field);
ptr = ptr[offset];
string result = *static_cast<string*>(ptr);
but that seems to be out since field
's value doesn't vary across calls. What am I missing? How exactly is this specific operation described by the standard?