Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
404 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...