1

how can I access a filed by just having that field's name stored in a string? e.g. I have function template, an object and a string passed to that function:

class MyClass
{
public:
    MyClass(int data)
    {
        this->data = data;
    }
private:
    int data;
};


template <class T>
void foo(T& myobj, string property_name)
{
    //do sth
    cout << myobj.getval(property_name) << endl;
}

how can I do something like this?
Mohammad
  • 11
  • 3
  • 1
    There is no automatic way. – HolyBlackCat Dec 30 '21 at 21:32
  • Don't use member variables, but store the fields in a map. E.g. std::map from std::string to std::any – Sebastian Dec 30 '21 at 21:34
  • if i wanna add a method to each class should it be string? or can I do sth else? – Mohammad Dec 30 '21 at 21:36
  • Methods are called member functions in C++. You want to add one to each class? The same function for each class or different ones? To really each class (not possible) or to your custom classes only? What would be string? The return value? – Sebastian Dec 30 '21 at 21:40
  • C++ 'classes' are one level below the classes you find in interpreted languages. You can get the same behaviour in C++, if you want, but for it you won't be accessing the actual C++ 'fields' dynamically, but something that acts like fields and is more flexible and is implemented/implementable on top of the C++ fields. – Sebastian Dec 30 '21 at 21:46
  • Thanks @Sebastian! I think the std::math is a good solution to my problem. – Mohammad Jan 10 '22 at 19:02
  • `std::math`? You mean `std::map`? – Sebastian Jan 10 '22 at 19:06
  • 1
    Excuse me! yes I meant std::map – Mohammad Jan 12 '22 at 20:56
  • Five ways to store properties of several types are a) use one map per type; b) use std::variant; c) use std::any; d) for class types, derive from a common base class with virtual member functions; e) serialize the types to a string – Sebastian Jan 12 '22 at 22:22

0 Answers0