简体   繁体   中英

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

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM