0

我已经使用 C++ 很长时间了,但我最近才开始使用 lambdas。我有以下示例,这给我带来了一些麻烦(为什么会这样)。请记住,这只是一个示例片段。

double TwoParams::shiftedSquaredSum(double izero, double particlePotential, double shift)
{
    double sum=0;
    bool ok = true;
    int count = 0;
    double temp;

    //the term with index K in the RMS total sum  <------------- MY LAMBDA 
    auto rms = [](double exp, double th) {
        return std::pow(exp - th, 2.0);
    };

    for (int i = 0; i < Lu_163_Exp.dim1 && ok; ++i)
    {
        temp = rms(Lu_163_Exp.spin1Exp[i], band1EnergyShifted(Lu_163_Exp.spin1Exp[i], izero, particlePotential, shift));
        if (isnan(temp))
        {
            ok = 0;
            break;
        }
        if (!isnan(temp))
        {
            count++;
            sum += temp;
        }
    }
return sum;

这些术语Lu_163_Exp.spin1Exp[i]是位于另一个类中的一些常量双向量,我想从多个.cpp源访问它,并且band1EnergyShifted()是在TwoParams类中声明的方法。这种方法也是双重类型的。

现在,我的问题是:如果rmslambda 有参数expthdouble 类型,编译成功,但如果我有

 auto rms = [](auto exp, auto th) {    // <--------------- I initially wanted to set them with auto type
        return std::pow(exp - th, 2.0);
    };

编译给出错误:

twoParamsEnergies.cpp: In member function ‘double TwoParams::shiftedSquaredSum(double, double, double)’:
twoParamsEnergies.cpp:62:24: error: parameter declared ‘auto’
     auto rms = [](auto exp, auto th) {
                        ^
twoParamsEnergies.cpp:62:34: error: parameter declared ‘auto’
     auto rms = [](auto exp, auto th) {
                                  ^
twoParamsEnergies.cpp: In lambda function:
twoParamsEnergies.cpp:63:31: error: ‘th’ was not declared in this scope
         return std::pow(exp - th, 2.0);
                               ^
twoParamsEnergies.cpp: In member function ‘double TwoParams::shiftedSquaredSum(double, double, double)’:
twoParamsEnergies.cpp:68:119: error: no match for call to ‘(TwoParams::shiftedSquaredSum(double, double, double)::__lambda0) (double&, double)’
         temp = rms(Lu_163_Exp.spin1Exp[i], band1EnergyShifted(Lu_163_Exp.spin1Exp[i], izero, particlePotential, shift));

据我到目前为止所了解的,编译器应该自己弄清楚参数的类型exp以及th参数是否为自动类型。我错过了什么吗?

先感谢您!

4

0 回答 0