mardi 19 décembre 2017

Accessor functions by data member assignment

I want to enhance members of C++ classes so that assignment from/to them results in the call of a custom getter/setter.

Like

class Class
{ 
public:
    int Member;
    void SetMember(int Value); // TBD
    int GetMember(); // TBD
}

and

Class Instance;
Instance.Member= 3; // Causes a call to SetMember(3);
int Data= Instance.Member; // Causes a call to GetMember();

I have found a way to force a function call upon member assignment, by turning the member type to a class holding a private value, and overloading the cast operator for reading and the assignment operator for writing.

class WrapInt
{
public: 
    operator int() const { return Value; }
    void operator=(const int Assign) { Value= Assign; }
private:
    int Value;
}

This works, but in a generic way, I cannot customize the getters/setters per member but only per data type.

Do you see a way to refine so that I can write different accessors for different members of the same type ?

Aucun commentaire:

Enregistrer un commentaire