2

Having structure

struct Person{
   Person(int a , int i):age(a),id(i){};
   int age;
   int id;
}

Is it possible to pass which argument to exctract as argument in function? Something like

int extract( Person * p , param ){
    return p -> param;
} 

which would return id , if used it like

extract( p , "id" )

and age if i used it like

exctract(p , "age")

Is something like this possible in c++?

sergej
  • 17,147
  • 6
  • 52
  • 89
J.dd
  • 145
  • 15
  • 4
    Looks like a duplicate of [How can I call a method given only its name](http://stackoverflow.com/questions/19473313/how-to-call-a-function-by-its-name-stdstring-in-c) – Nikita Nov 06 '16 at 22:48

3 Answers3

4

You can use pointers to class members.

struct Person{
    Person(int a , int i):age(a),id(i){};
    int age;
    int id;
};

int extract(Person* p, int Person::* param)
{
    return p->*param;
}

and you'd use it like this:

extract(p, &Person::id);

demo

krzaq
  • 16,240
  • 4
  • 46
  • 61
0

You can do it with preprocessor abuse, and more notably, without using string comparisons, which seems like what you want to do.

#include <iostream>

#define extract(p, i) (p->i)

struct Person{
  int age;
  int id;
};

int main() {
  Person p;
  p.age = 100;
  p.id = 30;
  std::cout << extract((&p), id) << '\n' << extract((&p), age) << '\n';
}

Not that I suggest doing this, though.

druckermanly
  • 2,694
  • 15
  • 27
-1

You can use Map<char*, int>which can do exactly that (but arguably is a bit of owerkill). Or just plain char[][] and check equality with the parameter in a for loop.

Rasty
  • 301
  • 1
  • 10