-1

I want to implement a function that can print out the value of one member variable (for example, 'aa') of struct ('Data') by it's name. I try to use the macro definition as follows, but failed. Is there a simple way to implement it?

#include <string>
#include <iostream>
using namespace std;
struct Data
{
    int aa;
    int bb;
    int cc;
    Data(): aa(1),bb(2),cc(3) {};
};

#define Param(a,b) a.##b

void Process(Data& data, const string& name)
{
    cout << Param(data, name) << endl;
}

void main()
{
    Data data;

    Process(data, "aa");//I want print the value of Data.aa
    Process(data, "bb");//I want print the value of Data.bb
    Process(data, "cc");//I want print the value of Data.cc
}
Logic
  • 11
  • 2
  • You can declare functions inside a struct, just as you whould do in a class – k_kaz Oct 21 '16 at 06:28
  • Just call the process function with parameter `data.aa` – Prasanna Oct 21 '16 at 06:30
  • The actual situation is more complex than this, can not be called directly. – Logic Oct 21 '16 at 06:35
  • No, C++ does not provide a simple way to implement this. In fact, as far as i know it provides no way of implementing this at all – Henningsson Oct 21 '16 at 06:37
  • 2
    Possible duplicate of [How to call a function by its name (std::string) in C++?](http://stackoverflow.com/questions/19473313/how-to-call-a-function-by-its-name-stdstring-in-c) – Sambuca Oct 21 '16 at 06:37

2 Answers2

2

This is not possible in C++.

This kind of usage is generally seen in scripting languages.

In C++ the variable names are constructed at compile time.

Chaitanya Sama
  • 330
  • 3
  • 13
0

Your original code sample makes no sense to me because if you call Param(name) then the compiler has to know what instance of Data it has to use to determine the value of the member variable you want to get the value of (but I'm neither an expert using macros nor do I like them very much).

I tried to solve your problem using the following approach:

struct Data
{
    int aa;
};

#define GetMemberValue(d, n) d.##n

int main()
{
    Data d;

    d.aa = 3;

    int i = GetMemberValue(d, aa);
}

At least this approach returns the right result in this case.

Another thing is that you stated that you cannot call the member variables directly i.e. data.aa so you might run into the same issue using the macro. It's just a guess as I don't know the original code you're using.

TorbenJ
  • 4,462
  • 11
  • 47
  • 84