C ++中的自定义事件? [英] Custom events in C++?

查看:124
本文介绍了C ++中的自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以用C ++创建自定义事件吗?例如,假设我有变量X和变量Y.每当X改变时,我想执行一个将Y设置为3的函数。有没有办法创建这样的触发器/事件? (触发器在某些数据库中很常见)

Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)

推荐答案

这基本上是Observer模式的一个实例(如其他人已经提到和链接) 。但是,您可以使用模板魔术来呈现出更多的语法可调性。考虑一下...

This is basically an instance of the Observer pattern (as others have mentioned and linked). However, you can use template magic to render it a little more syntactically palettable. Consider something like...

template <typename T>
class Observable
{
  T underlying;

public:
  Observable<T>& operator=(const T &rhs) {
   underlying = rhs;
   fireObservers();

   return *this;
  }
  operator T() { return underlying; }

  void addObserver(ObsType obs) { ... }
  void fireObservers() { /* Pass every event handler a const & to this instance /* }
};

然后你可以写...

Observable<int> x;
x.registerObserver(...);

x = 5;
int y = x;

用于编写观察器回调函数的方法完全取决于您;我建议 http://www.boost.org 的功能或功能模块(您也可以使用简单的函子) 。我也提醒您注意这种类型的操作员重载。虽然它可以使某些编码风格更清晰,但是鲁莽地使用一个渲染像

What method you use to write your observer callback functions are entirely up to you; I suggest http://www.boost.org's function or functional modules (you can also use simple functors). I also caution you to be careful about this type of operator overloading. Whilst it can make certain coding styles clearer, reckless use an render something like

seemLikeAnIntToMe = 10;

seemsLikeAnIntToMe = 10;

非常昂贵的操作,可能会爆炸,并在未来几年内引起调试恶梦。

a very expensive operation, that might well explode, and cause debugging nightmares for years to come.

这篇关于C ++中的自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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