gpt4 book ai didi

c++ - 更自然的 boost::bind 替代方案?

转载 作者:太空狗 更新时间:2023-10-29 20:49:25 25 4
gpt4 key购买 nike

不要误会我的意思:Boost 的 bind() 很棒。

但我确实讨厌用它来编写和阅读代码,并且我已经放弃了希望我的同事永远理解/使用它的希望。

我最终得到这样的代码:

btn.clicked.connect(bind(&BetBar::placeBet, this, bet_id));
animator.eachFrame.connect(bind(&Widget::move, buttons[bet_id]));

虽然合乎逻辑,但与我所说的好代码相去甚远。

为了演示...在 C++1x 中,我们将使用:

btn.clicked.connect([&](int bet_id){ placeBet(bet_id); })
animator.eachFrame.connect([&](Point newPos) { buttons[bet_id].move(newPos) })

一个好的 DSL 可能看起来像这样:

on(btn.clicked) placeBet(bet_id);
on(animator.eachFrame) buttons[bet_id].move(eachFrame::newPos);

您如何处理 C++ 中的绑定(bind)?你只是接受给你带来的 boost 吗?

最佳答案

您似乎想要以下内容:

  • 隐式绑定(bind)到 this
  • 与存储绑定(bind)的函数调用关联的括号的替代方法。
  • 自动识别您的 lambda 表达式中绑定(bind)了哪些参数。

第一个在今天的 C++ 中非常困难,因为 this在极少数情况下是隐式的,你当然不能将它隐式地传递给函数。 IE。你不能用库函数来实现这个,但你可以用宏来实现。尽管如此,它还是很丑陋。

第二部分要容易得多:

button.clicked.handler = bind(BetBar::placeBet, this, bet_id);

这只需要 handler.operator=(boost::function<void(*)()> const&)

第三个又难了,因为你刚刚又设计了一个两阶段名称查找的案例。这对模板来说已经够难的了。 boost 的 _1 技巧通过明确指出以后应绑定(bind)哪些参数来起作用。但是,_1 作为名称并不神奇。它基本上是一个返回 boost::arg<1> 的免费函数。因此,通过对 animator.eachFrame.newPos 的适当定义,可以使以下内容等效:

animator.eachFrame.handler = bind(&Widget::move, buttons[bet_id], _1)
animator.eachFrame.handler = bind(&Widget::move, buttons[bet_id], animator.eachFrame.newPos)

关于c++ - 更自然的 boost::bind 替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/500819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com