Access a member in a struct via a variable in C++

Viewed 317

I have a struct with two members, for example:

struct DataSet {
    int x;
    int y;
};

..., and i have to access those in a method, but only one at a time, for example:

void foo(StructMember dsm) { // ("StructMember" does not exist)
    DataSet ds;
    ds.x = 4;
    ds.y = 6;

    std::cout << ds.dsm * ds.dsm << std::endl;
}
foo(x);
foo(y);

Output i wish to have:

16
36

What should I do when I have to solve a problem like this? Is there a data type which can access a member?

1 Answers

Yes, you can use a pointer-to-member. The syntax for the type is TypeOfMember TypeOfStruct::*, and to access you do struct_variable.*pointer_variable

using StructMember = int DataSet::*;  // Pointer to a member of `DataSet` of type `int`

void foo(StructMember dsm) {
    DataSet ds;
    ds.x = 4;
    ds.y = 6;

    std::cout << ds.*dsm * ds.*dsm << std::endl;
}

int main() {
    foo(&DataSet::x);
    foo(&DataSet::y);
}
Related