Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c++ - Automatically call function when variable changes

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...