I've been working with C++ for a long time, but I've only recently started to play with lambdas. I have the following example which gives me some trouble figuring it out (why does it behave like this). Keep in mind that this is just an example snippet.
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;
The terms Lu_163_Exp.spin1Exp[i]
are some constant double vectors located in another class which I want to access it from multple .cpp
sources, and band1EnergyShifted()
is a method declared in the TwoParams
class. This method is also of double type.
Now, my issue is this: If the rms
lambda has the parameters exp
and th
of double type, the compilation is succesfull, but if I have it
auto rms = [](auto exp, auto th) { // <--------------- I initially wanted to set them with auto type
return std::pow(exp - th, 2.0);
};
compilation gives erros:
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));
From what I've understood so far, the compiler should figure it out by itself the type of exp
and th
if the parameters are of auto type. Am I missing something?
Thank you in advance!
Aucun commentaire:
Enregistrer un commentaire