2

我想使用 Boost.Phoenix 创建一个 lambda 函数,该函数由几行代码组成,然后“返回”一个值,以便我可以将它与std::transform.

像这样:

std::transform(a.begin(), a.end(), b.begin(),
        (
            //Do something complicated here with the elements of a:
            statement1,
            statement2,
            statement3
            //Is there a way to return a value here?
        )
        );

std::for_each这样可以完美地工作,但是由于逗号运算符返回,因此std::transform无法编译void。如何从这样的 lambda 函数返回值?


编辑:我更改了代码片段,因为我首先写的内容​​导致了对我想要做什么的误解。

4

2 回答 2

1

不,这是不可能的。来自Boost.Phoenix v2 声明文档

与惰性函数和惰性运算符不同,惰性语句总是返回 void。

(请注意,同样的断言也在 Boost.Phoenix v3 文档中。)

于 2011-05-24T17:49:47.993 回答
1

在函数式编程中,改变状态不是意图。但是,for_each您可以不使用 ,而使用accumulate。累积意味着您有一个“起始值”(例如 m=1,n=0),以及一个将值“添加”到输出值的函数:

#include <vector>

struct MN { int m, n; 
  MN(int m,int n):m(m),n(n){}
  static MN accumulate( MN accumulator, int value ) {
     return MN( accumulator.m + value, accumulator.n * value );
  }
}; // your 'state'

int main(){
  std::vector<int> v(10,10); // { 10, 10, ... }
  MN result = std::accumulate( v.begin(), v.end(), MN(0,1), MN::accumulate );
  printf("%d %d", result.m, result.n );
}

我对 Phoenix 不熟悉,但可能有一种方法可以MN::accumulate根据它来定义功能。

于 2011-05-24T18:49:11.890 回答