简体   繁体   English

什么时候计算 lambda 函数中的表达式?

[英]when is an expression in a lambda function evaluated?

Given this little snippet: a and b are not known at compile time.鉴于这个小片段: a 和 b 在编译时是未知的。 Map is a mapping function for the vector, mapping the lambda function over each element of bar. Map 是向量的映射函数,将 lambda 函数映射到 bar 的每个元素上。 Supposing fooify() is called ... Will a/b be evaluated as a constant before executing map() or will it be evaluated every time the lambda is called?假设 fooify() 被调用...... a/b 在执行 map() 之前会被评估为一个常量还是每次 lambda 被调用时都会被评估?

Foo::fooify(vector<float>& bar){
  float a = getA();
  float b = getB();
  map(bar, [&](float c){c*(a/b);});
}

I suspect a/b will be evaluated in every call to the lambda function.我怀疑在每次调用 lambda 函数时都会评估a/b You can make sure that it is evaluated only once by using:您可以使用以下方法确保它只评估一次:

Foo::fooify(vector<float>& bar){
  float a = getA();
  float b = getB();
  float ab = a/b;
  map(bar, [](float c){c*ab;});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM