变量更改时自动调用功能 [英] Automatically call function when variable changes

查看:54
本文介绍了变量更改时自动调用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中,是否有一种方法可以在变量值更改时自动调用函数?

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

推荐答案

c ++中是否有一个函数,当变量被更改时它会自动调用一个函数?

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_;
};

如诺亚(Noah)在评论中指出,

As Noah noted in a comment,

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

(或者,如果您的编译器拥有它,则std::tr1::functionstd::function)将对此进行极大的改进,因为它允许调用各种兼容"函数. (例如,它使用boost/std::/tr1::bind<>启用各种魔术来调用成员函数,然后调用诸如此类.)

(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.)

还请注意,正如adf88在他的评论中所说,这只是要求的(监视变量的写访问权限),而绝不是完整的属性实现.实际上,尽管C ++倾向于尽可能多地在库中实现语言而在语言中尽可能少地实现,并且尽管有许多人(其中有些人很聪明)的尝试,但没有人找到在C ++中实现属性的方法. 作为库,而没有该语言的支持.

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.

这篇关于变量更改时自动调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆