How to access the getter and Setter methods of one class through another in a generic C++

Asked

Viewed 31 times

0

I would like to be able to assign and/or retrieve values of an object through another class, where I can declare which properties I would like to access, their types, the method to access the private attribute value and the method to assign the value.

I would like to store in a hash the name of the property and the methods to manipulate the value, in this way I could use generic class values by other entities, but I do not know if it is possible (I imagine so), and I do not know how to do.

The code below is not functional, it was based on an attempt I was making to try to implement a solution. Of the error can example of:

error: no matching function for call to 'Test<unsigned int>::Test(C&, const char [2], unsigned int (C::*)() const, void (C::*)(unsigned int))'
     auto t1 = new Test<unsigned int>(c, "a", &C::getA, &C::setA);

Below the code snippet

#include <string>
#include <map>

class C {
public:
    unsigned int getA() const {
        return a;
    }

    void setA(unsigned int value) {
        C::a = value;
    }

    const std::string &getB() {
        return b;
    }

    void setB(const std::string &value) {
        C::b = value;
    }

private:
    unsigned int a;
    std::string b;
};

template<typename T>
class Test {
public:
    Test(T t, const std::string attribute, const T (*getter)(), void (*setter)(T)) : t(t), attribute(attribute),
                                                                                      getter(getter), setter(setter) {}

    const std::string &getAttribute() const {
        return attribute;
    }

private:
    T t;
    std::string attribute;

    const T (*getter)();

    void (*setter)(T t);
};


int main(int argc, char **argv) {
    C c;
    auto t1 = new Test<unsigned int>(c, "a", &C::getA, &C::setA);
    auto t2 = new Test<std::string>(c, "b", &C::getB, &C::setB);
    std::map<std::string, std::string *> map;
    
    map.insert({t1.getAttribute, t1});
    map.insert({t2.getAttribute, t2});
}

So basically I have two questions is it possible to do this? if yes, how?

In this context for example if I needed to retrieve the value of "a" (variable) t1, I would like to go to the map and use the getter function pointer of the Test class

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.