代码之家  ›  专栏  ›  技术社区  ›  Pierre-olivier Gendraud

返回lambda表达式的方法中的转换错误

  •  2
  • Pierre-olivier Gendraud  · 技术社区  · 7 年前

    #include "iostream"
    #include  "functional"
    std::function<double (double)> retFun(double* a) {
         return [a](double x) { return x+*a; };
     }
    
     int main(){
    
     double*e = new double(3);
     std::cout << retFun(e)(3) << std::endl;}
    

    retFun 在对象中:

    .h

    class InternalVariables : public Page
    {
    private:
        std::function<double ()> retFun(double* a);
    };
    

    .清洁石油产品

    std::function<double ()> InternalVariables::retFun(double *a)
    {
        return [a](double b){ return b+ *a;};
    }
    

    我得到以下错误

    错误:无法将InternalVariables::retFun(double*)::_ulambda44{a}从InternalVariables::retFun(double*):::_ulambda44转换为std::函数 return[a](双b){return b+*a;};

    1 回复  |  直到 7 年前
        1
  •  6
  •   Vittorio Romeo    7 年前

    std::function<double ()> 意味着您的包装函数对象将不接受任何参数,并返回一个 double . [a](double b){ return b+ *a;} 并返回一个

    您应该将退货类型更改为 std::function<double (double)>


    也:

    • <...> . 例子: <iostream> .

    • 没有必要分配 在堆上获取指向它的指针。只需使用 & 在堆栈上。C++11中的分配应始终通过 new / delete .

    • 你可能只想回来 auto 而不是 std::function