In math, if z = x + y / 2
, then z
will always change whenever we replace the value of x
and y
. Can we do that in programming
You could write a class that encapsulates its state to update either when mutated or return the right result when requested :
#include
template
class DynamicCalc
{
public:
DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
_func(func)
, _memberOne(memberOne)
, _memberTwo(memberTwo)
{
}
void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
auto Retrieve() { return _func(_memberOne, _memberTwo); }
U GetMemberOne() { return _memberOne; }
V GetMemberTwo() { return _memberTwo; }
private:
T _func;
U _memberOne;
V _memberTwo;
};
int main() {
auto func = [](int x, int y) {
return x + y;
};
DynamicCalc c(func, 3, 5);
c.SetMemberOne(5);
std::cout << c.Retrieve();
}
In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.