我有一个程序,在对每个组件进行一些计算之后,我必须在屏幕上打印许多 STL 向量。所以我试图创建一个这样的函数:
template <typename a>
void printWith(vector<a> foo, a func(a)){
for_each(foo.begin(), foo.end(), [func](a x){cout << func(x) << " "; });
}
然后像这样使用它:
int main(){
vector<int> foo(4,0);
printWith(foo, [](int x) {return x + 1;});
return 0;
}
printWith
不幸的是,关于我在调用中放入的 lambda 表达式的类型,我遇到了编译错误:
g++ -std=gnu++0x -Wall -c vectest.cpp -o vectest.o
vectest.cpp: In function ‘int main()’:
vectest.cpp:16:41: error: no matching function for call to ‘printWith(std::vector<int>&, main()::<lambda(int)>)’
vectest.cpp:10:6: note: candidate is: void printWith()
make: *** [vectest.o] Error 1
当然,如果我这样做:
int sumOne(int x) {return x+1;}
然后printWith(foo, sumOne);
按预期工作。我认为 lambda 表达式的类型将是具有推断返回类型的函数的类型。我也认为我可以在任何可以拟合正常函数的地方安装 lambda。我该如何进行这项工作?