【问题标题】:Lambda-function as a parameterLambda 函数作为参数
【发布时间】:2021-08-30 12:26:37
【问题描述】:

我是第一次使用 lambda。我应该写一个函数 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()::' 转换为 'int'

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

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

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

【问题讨论】:

  • Sea::Grid2D&lt;T&gt; 中的TT operation 中的T 是否应该始终是同一类型?目前,您正在强制它们相同。

标签: c++ function templates lambda parameters


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    你已经实例化了Sea::Grid2D&lt;int&gt; - 也就是说,Tint - 这给了你:

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

    【讨论】: