[Solved] Call a function while setting value of a declarement [closed]


If you need to trigger a function call on assignment, you can wrap the type in a class that overrides the assignment operator; note that you may want to override more than just assignment, this is just an example and not a style guide 🙂

#include <iostream>

template<class T> class wrap
{
private:
  T value;
  void (*fn)();
public:
  wrap(void (*_fn)()) { fn=_fn; }
  T& operator=(const T& in) { value = in; fn(); return value;}

  operator T() { return value; }
};

void func() {
  std::cout << "func() called!" << std::endl;
}

int main(void)
{
  wrap<int> i(func);
  i=5;                           // Assigns i and calls func()
  std::cout << i << std::endl;   // i is still usable as an int
}

> Output: 
>   func() called!
>   5

1

solved Call a function while setting value of a declarement [closed]