class A
{
int vel; //velocity
public:
A() : vel(51) {}
class VelocityProxy
{
int &Vel;
VelocityProxy(int &v) : Vel(v) {}
public:
VelocityProxy(const VelocityProxy &vp) : Vel(vp.Vel) {}
VelocityProxy &operator=(constint &v)
{
Vel = v > 100 ? 100 : v;
}
VelocityProxy &operator=(const VelocityProxy &vp)
{
Vel = vp.Vel;
}
operatorint()
{
return(Vel);
}
VelocityProxy &operator*=(constint &v)
{
Vel *= v;
Vel = Vel > 100 ? 100 : Vel;
}
//and other operators an int normally has
};
VelocityProxy &Velocity()
{
return(VelocityProxy(vel));
}
};
//code by user of your library
A obj; //vel == 51
obj.Velocity() *= 2; //VelocityProxy makes sure 51*2->102 goes to 100
Do you think this is a good idea to make life easier for the users of your library? (Just the concept?)
It doesn't seem to make it any easier. Just make the data public if you want that to be doable. The only time I can think of that you might want to do that is if you need to do different stuff for operator *= or something on an stored int or something.
You are wasting time. By using a reference now you've got to code the copy constructor and assingment operator. Also, there is a bigger problem here:
1 2 3
VelocityProxy &Velocity()
{
return(VelocityProxy(vel)); //error: non-const reference from an rvalue
Easy fix VelocityProxy Velocity(); //return an object
I don't see an advantage from making it an inner class either.
Still you could simply do
1 2 3
struct A{
velocity_clamp vel;
};
¿What about Demeter's Law and Tell, don't ask instead of getters/setters?
Edit:
The only advantage that I see is if you want to do different kind of things to the variable
By instance, now you are making a clamping and later you may want to wrap it.
It seems a little like the 'strategy pattern'.