相关疑难解决方法(0)

C++ 0x lambda按值捕获总是const?

有没有办法按值捕获,并使捕获的值非const?我有一个库函子,我想捕获并调用一个非常量但应该是的方法.

以下不编译,但使foo :: operator()const修复它.

struct foo
{
  bool operator () ( const bool & a )
  {
    return a;
  }
};


int _tmain(int argc, _TCHAR* argv[])
{
  foo afoo;

  auto bar = [=] () -> bool
    {
      afoo(true);
    };

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ lambda const c++11

95
推荐指数
1
解决办法
2万
查看次数

无法通过Lambda中的值捕获随机分布和生成器?

下面的代码工作正常

#include <iostream>
#include <random>

int main() {
    std::default_random_engine generator;
    std::normal_distribution<double> distribution(5.0, 2.0);
    std::vector<double> v(100);

    std::generate(v.begin(), v.end(), [&] () { return distribution(generator); });

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,将lambda的捕获列表更改为[=]or [&, distribution]或or [&, generator]会导致

rand.cpp:9:59: error: no matching function for call to object of type 'const std::normal_distribution<double>'
error: assigning to 'double' from incompatible type 'void'
Run Code Online (Sandbox Code Playgroud)

是否存在无法通过Lambda中的值捕获的某些对象?

c++ lambda c++11

4
推荐指数
2
解决办法
276
查看次数

标签 统计

c++ ×2

c++11 ×2

lambda ×2

const ×1