Aaron Aaron - 1 month ago 6
C++ Question

Is it possible to pass a struct's member variable as parameter

I am trying to associate a struct's member variable with a class. So that when I create a new class, I can specify that it is associated with this member variable in a struct. For example:

struct A {
int a;
int b;
};

static A a[2];
a[0].a = 1;
a[0].b = 2;
a[1].a = 3;
a[1].b = 4;

class foo {
public:
foo(int index, ???) {
c = a[index].???; //Is it possible to define the 2nd parameter as a getter of struct A's member? So this line could resolve to either a[index].a or a[index].b?
}
private:
int c;
};


So that:


  • new foo(0, ???) would set c to 1 given ??? refer to A::a

  • new foo(0, ???) would set c to 2 given ??? refer to A::b

  • new foo(1, ???) would set c to 3 given ??? refer to A::a

  • new foo(1, ???) would set c to 4 given ??? refer to A::b


VTT VTT
Answer Source

Yes, it is possible, you need to pass a data member pointer:

#include <iostream>

struct A
{
    int a;
    int b;
};

static A a[2]
{
    1, 2
,   3, 4
};

class foo
{
    public: int c;

    public:
    foo(int const index, int A::* const p_field)
    {
        c = a[index].*p_field;
    }
};

int main()
{
    foo const f1(0, &A::a);
    ::std::cout << f1.c << ::std::endl;
    foo const f2(0, &A::b);
    ::std::cout << f2.c << ::std::endl;
    foo const f3(1, &A::a);
    ::std::cout << f3.c << ::std::endl;
    foo const f4(1, &A::b);
    ::std::cout << f4.c << ::std::endl;
    return 0;
}

Check this code at online compiler