Lambda函数作为参数
我第一次使用 lambdas。我应该编写一个函数 walk() ,它以 lambda 函数为参数。
在标题中,我将上述函数声明为:
template<class T>
void walk(T operation) const;
我们应该在 .inl 中定义函数,我是这样做的:
template<class T>
void Sea::Grid2D<T>::walk(T operation) const{
for(auto a : Sea::Grid2D<T>::grid){
operation(a);
}
}
我的问题在这一点上出现,因为我们有一个测试类,它像这样调用我们的 walk() 函数。
grid.walk([&](int const &cell) { sum += cell; });
对 walk 函数的调用会导致以下错误:
错误:无法将“testWalkAndFilter()::<lambda(const int&)>”转换为“int”
43 | grid.walk([&](int const &cell) { sum += cell; });
我将如何将我的 lambda 函数转换为 int 或需要的参数?
在试图解决这个问题的同时。我还尝试为 walk 函数提供一个引用或一个 const 引用参数,但到目前为止没有任何效果。
回答
您已经实例化Sea::Grid2D<int>- 即T是int- 这给了你:
void Sea::Grid2D<int>::walk(int operation) const {
for(auto a : Sea::Grid2D<int>::grid) {
operation(a);
}
}
很明显有一个打字问题 - 操作的类型不应该与您的网格元素的类型相同。
由于您在类模板中有一个函数模板,因此您需要两个“级别”的模板,例如:
template<class T>
class Grid2D {
...
template <class Fn>
void walk(Fn operation) const;
...
};
...
template<class T>
template <class Fn>
void Sea::Grid2D<T>::walk(Fn operation) const {
for(auto a : grid) {
operation(a);
}
}