Jon Jon - 4 months ago 9
C++ Question

How to pass the name of a member from a struct as an argument into a function using C++?

I have exhausted my patience trying to find this particular question .

I am trying to input the name of a particular member from a structure into a function.

My first thought was that this is impossible because a function's arguments needs to be a variable declared and defined in RAM. Yet the computer is able to interpret the location of a "member" for each instance given the members name.

The following is a arbitrary program where I created an array of structures and the program will some how input all of the data for each member in the structure for each instance in the array. It will then attempt to display all of the content for a particular member in the array. It is incomplete because I don't know how to make it work.

#include theUsual

// global variables
const int SIZE = 10;

// structures
struct structureExample
{
dataType member1;
dataType member2;
...
};

// functions
void inputData(structureExample s[], int size);
void displayMember( dataType member, structureExample s[], int size);

int main
{
structureExample sE[SIZE];
dataType memberName = member1 // member1 from the declared struct structureExample

inputData(sE,SIZE);

displayMember(memberName, sE, SIZE);

system("PAUSE");
return 0;
}

// inputs all the data for all members in an array of structure examples
void inputData(structureExample s[], int size)
{
...
}

// display's all of the content of a particular member from an array
void displayMember( dataType member, structureExample s[], int size)
{
for (int i = 0; i<size; i++)
{
cout << s[i].member << endl;
}
}


So given any member name from structureExample into displayMember, it will display the all of the content of that member for every unit in the array.

I have allot of questions about this but the biggest two are, can this even work? If so how could I make this work? Examples would be appreciated.

Thanks in advance!

Answer

It seems you want pointer on member:

struct structureExample 
{
   int member1;
   float member2;
};

template<typename M>
void displayMember(M structureExample::*member, structureExample s[], int size)
{
   for (int i = 0; i < size; i++)
   {
      std::cout << s[i].*member << std::endl;
   }
}

int main()
{
    structureExample sE[SIZE];
    auto member = &structureExample::member1;

    inputData(sE,SIZE);

    displayMember(member, sE, SIZE);
}
Comments