Lambda-function 作为参数

Lambda-function as a parameter

我是第一次使用 lambda。我应该编写一个函数 walk() ,它将 lambda 函数作为参数。

在 header 中,我将上述函数声明为:

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);
    }
}

此时我的问题出现了,因为我们得到了一个测试 class,它像这样调用我们的 walk() 函数。

    grid.walk([&](int const &cell) { sum += cell; });

walk 函数的调用导致以下错误:

error: cannot convert 'testWalkAndFilter()::<lambda(const int&)>' to 'int'

43 | grid.walk([&](int const &cell) { sum += cell; });

如何将我的 lambda 函数转换为 int 或所需参数?

正在尝试解决这个问题。我也试过给 walk 函数一个引用,或者一个 const 引用参数,但到目前为止没有任何效果。

您可能将名称 T 用于 2 个不同的参数(我猜一个在 Grid2D class 级别,一个在这个函数上)。

template<class T>
void Sea::Grid2D<T>::walk(T operation) const{

    for(auto a : Sea::Grid2D<T>::grid){

将此重命名为其他名称。比如,U。 但如果可能的话,最好给他们起一个能反映意图的名字。比如,CallableOperation.

您已经实例化了 Sea::Grid2D<int> - 也就是说,Tint - 这给了您:

void Sea::Grid2D<int>::walk(int operation) const {
    for(auto a : Sea::Grid2D<int>::grid) {
        operation(a);
    }
}

这很明显存在输入问题 - 操作类型不应与网格元素的类型相同。

由于您在 class 模板中有一个函数模板,您需要两个“级别”的模板,例如:

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);
    }
}