更改变量后的C ++自动调用函数 [英] C++ auto call function after change variable

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

问题描述

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

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

推荐答案


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

正如诺亚在评论中指出,

As Noah noted in a comment,

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

(或者,如果你的编译器有它, std :: tr1 ::函数 std :: function )会大大改善,因为它允许调用所有种类的兼容函数。 (例如,它使用 boost / std :: / tr1 :: bind<> 来调用成员函数和whatnot。)

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

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

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