Search code examples
c++classclass-members

convert string/character to class member/method in c++


Is there a way to convert string or characters to class member/member functions to access them dynamically?

for ex. this particular code,

 #include <iostream>
 #include <map>

 using namespace std;

 class agnt {
 public:
 int x, y;
 agnt(int a=0, int b=0) : x(a), y(b) {}
 };


 int main() {
      map<int,agnt> agntID;
      agnt temp;
      temp.x=1;
      temp.y=5;

      agntID[1]=temp;

      for(char tmp='x'; tmp<'z'; tmp++) {
         cout<<agntID[1].tmp<<'\n';     //Here I get the following error: tmp is
         }                              //not a member of class agnt
 }

Is there a way to convert the character 'tmp' such that it is identified as a class member? Any tips or solution will be appreciated.


Solution

  • You can't do this in C++ because it's a statically-typed language. One way to get this sort of behaviour is to provide accessing wrappers:

    template <char c>
    struct getter {
    };
    
    
    template <>
    struct getter<'x'> { 
       static int get(const agnt &theAgnt) {
          return theAgnt.x;
       }
    };
    
    
    template <>
    struct getter<'y'> { 
       static int get(const agnt &theAgnt) {
          return theAgnt.y;
       }
    };
    
    template <char c>
    int get(const agnt &theAgnt) {
        return getter<c>::get(theAgnt);
    }
    

    And call like:

    agnt temp;
    //... set members
    std::cout << get<'x'>(temp) << std::endl;
    

    However, the for loop won't work the way you expect, because the template parameters need to be determined at compile time. Also, you can't just request any old thing, unless you define a get function in the unspecialised getter which returns some sort of NULL-indicator, like INT_MIN.

    However, this is all really a hack to get something vaguely similar to a dynamic language. But it's not really anything different from just referencing temp.x. Instead, you should try to adhere to C++ conventions and enjoy the static typing!