Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically call function when variable changes

Tags:

c++

function

Is there a way in c++ to automatically call a function when a variable's value changes?

like image 250
stefan Avatar asked Jul 01 '10 15:07

stefan


3 Answers

If the variable has a class type, you can overload its operator =() function. You cannot do this if the variable is a primitive type.

like image 144
David R Tribble Avatar answered Sep 17 '22 16:09

David R Tribble


Is there a function in c++ that when a variable got changed it automatically call a function?

No, not that I could think of. You can, however, wrap access to the variable in a suitable wrapper which allows you to hook into assignment.
Something like this:

//Beware, brain-compiled code ahead!
template<typename T>
class assignment_hook {
public:
  typedef void (hook_t)(const T& old_value, const T& new_value);

  assignment_hook(T& value, hook_t hook) : ref_(value), hook_(hook)  {}

  T& operator=(const T& rhs)
  {
     hook_(ref_,rhs);
     ref_ = rhs;
  }
private:
  // I'd rather not want to think about copying this
  assignment_hook(const assignment_hook&);
  void operator=(const assignment_hook&);

  T& ref_;
  hook_t hook_;
};

As Noah noted in a comment,

typedef boost::function<void(const T&,const T&)> hook_t;

(or, if your compiler has it, std::tr1::function or std::function) would greatly improve on that, because it allows all kinds of "compatible" functions to be called. (For example, it enables all kinds of magic using boost/std::/tr1::bind<> to call member functions and whatnot.)

Also note that, as adf88 said in his comments, this just does what was asked for (monitor write access to a variable) and is by no means a full-fledged property implementation. In fact, despite C++' attitude to implement as much as possible in libraries and as little as possible in the language, and despite the attempts of many people (some of them rather smart ones), nobody has found a way to implement properties in C++ as a library, without support from the language.

like image 25
sbi Avatar answered Sep 18 '22 16:09

sbi


In one word; no.

But what you should do is wrap the variable into a class (i'm not going to suggest operator overloading), and change it via a set(...) function. Then you simply call the function from the set function.

like image 31
Viktor Sehr Avatar answered Sep 19 '22 16:09

Viktor Sehr