简体   繁体   中英

C++ Pass struct member as argument

I have a function which calculates a struct based on input parameters. Is it possible to write a function which returns only a certain variable of the calculated struct by passing the desired variable as an argument? The problem is that the struct has to be created and calculated INSIDE the function, so I only know the future variable names of the struct's members.

Essentially what I want is to replace the following hard-coded "->member1" part by a variable which I have as an argument to the main "DoSomethingSpecific" function.

double DoSomethingSpecific()
{
  struct *s = CalculateStruct();
  DoSomethingElse(s->member1);
}

EDIT: I created a minimal example based on an answer which works now and solves the substantial problem of passing struct members as variables to function without creating the struct itsself. However, the data type (int) has to be known before in this case (otherwise templates would help if needed)

#include <iostream>
using namespace std;

struct MyStruct
{
   int a;
   int b;
};

int GetVariable(int MyStruct::* field)
{
   MyStruct *_myStruct = new MyStruct();
   _myStruct ->a = 1;
   _myStruct ->b = 2;

   return _myStruct->*field;
}

int main( )
{
   int my_variable = GetVariable(&MyStruct::a); 
   return 0;   
}  

You can pass in a pointer-to-data-member:

double DoSomethingSpecific(double Struct::* field)
{
  Struct *s = CalculateStruct();
  DoSomethingElse(s->*field);
}

Then to call it:

DoSomethingSpecific(&Struct::member1);

Edit, a fix based on your edited question:

int GetVariable(int MyStruct::* field)
{
    MyStruct *_myStruct = new MyStruct();
    _myStruct->a = 1;
    _myStruct->b = 2;

    return _myStruct->*field;
}

If you know its type you can pass a pointer to it. When constructing the Struct you initialize the member using the pointer.

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