Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 388
Adrian Avatar asked Apr 01 '20 23:04

Adrian


People also ask

How do you access a member of a struct variable?

Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures. Nested Structures are allowed in C Programming Language.

How will you access the member of a structure object?

Structure members are accessed using dot (.) operator.

Which operator allows you to access variables in a struct?

An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union.

Can you pass a struct by value in C?

A struct can be either passed/returned by value or passed/returned by reference (via a pointer) in C. The general consensus seems to be that the former can be applied to small structs without penalty in most cases.


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);
}
like image 62
Artyer Avatar answered Oct 18 '22 01:10

Artyer