加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C lambda – 捕获成员变量

发布时间:2020-12-16 05:42:26 所属栏目:百科 来源:网络整理
导读:我有一个类具有指向内核函数的函数指针,可以从外部改变. class Bar { public: int i;}class Foo { public: std::functiondouble() kernel; Bar bar; };int main(){ Foo f; f.kernel = []() - double { return i * i; }; //this is not working obviously} 如
我有一个类具有指向内核函数的函数指针,可以从外部改变.
class Bar 
{
   public:
     int i;
}

class Foo 
{
   public:
     std::function<double()> kernel;
     Bar bar;         
};

int main()
{

  Foo f;
  f.kernel = []() -> double { return i * i; }; //this is not working obviously

}

如何实现“呈现”的行为,例如读取lambda中的类变量.我可以绕过它,通过f里面写f.bar.i,但这不是很好的解决方案.

解决方法

在C 14中你可以写成,
f.kernel = [&i = f.bar.i]() -> double { return i * i; };

如果你没有C 14,你可以创建另一个变量,

int &i = f.bar.i;
f.kernel = [&i]() -> double { return i*i; };

虽然传递f和写f.bar.i没有任何错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读