【问题标题】:How to call this Lambda function in C++ [duplicate]如何在 C++ 中调用此 Lambda 函数 [重复]
【发布时间】:2018-02-15 13:20:46
【问题描述】:

我在这个类的 protected void 函数中编写了一个 lambda 函数

class Tetris: protected TetrisArea<true>
{
public:
    Tetris(unsigned rx) : TetrisArea(rx), seq(),hiscore(0),hudtimer(0) {}
    virtual ~Tetris() { }

protected:
    // These variables should be local to GameLoop(),
    // but because of coroutines, they must be stored
    // in a persistent wrapper instead. Such persistent
    // wrapper is provided by the game object itself.
    Piece seq[4];

lambda 函数,

auto fx = [&seq]() {  seq[0].x=4;       seq[0].y=-1;
                        seq[1].x=Width;   seq[1].y=Height-4;
                        seq[2].x=Width+4; seq[2].y=Height-4; }; 

所以这就是问题所在。我收到了这些错误:

 error: capture of non-variable 'Tetris::seq' 
         auto fx = [&seq]() {  seq[0].x=4;       seq[0].y=-1;
 error: 'this' was not captured for this lambda function
     auto fx = [&seq]() {  seq[0].x=4;       seq[0].y=-1;

.. 以及函数中 seq[n] 的后续引用。

我尝试直接在 protected void 函数中键入代码,但尽管它可以编译,但它似乎无法正常工作,因为该程序来自他的俄罗斯方块 Dos 游戏中的 Youtube 频道 Bisqwit。

【问题讨论】:

  • 确实是重复的,我不搜索相关问题很糟糕!
  • 不过希望在不久的将来对其他人有用
  • 您还应该发布minimal reproducible example。该代码中没有受保护的方法。我猜你漏掉了那部分

标签: c++ lambda


【解决方案1】:

在读取时,您尝试捕获对象的成员而不捕获对象本身。将[&amp;seq] 更改为[this] 看看会发生什么。

【讨论】:

  • 感谢它仍然有效!真的很感激!
  • 如果你可以使用 C++14,还有一种使用初始化 lambda 捕获表达式的新方法:auto fx = [&amp;ref = seq]() { ref[0].x=4; etc. }
  • 其实可以说[&amp;seq = seq],然后按照原版继续。这种简单的名称重用在this answer 中应用于链接问题。
猜你喜欢
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
相关资源
最近更新 更多