Vinoth Kumar Vinoth Kumar - 3 months ago 6
C++ Question

Unexpected result when non type template parameter is used in the program without assigning to local variable?

Since direct floating point comparisons are risky, i am writing one wrapper class for checking relational operations for floating point numbers.

#include<iostream>
#include <cmath>

template<unsigned int round_off_digits=10>
class FloatRelationalOperators
{
private:
inline static double calcEpsilonValue()
{

int localVar=round_off_digits;

double withLocalVar=pow(10, (localVar * -1 ));
double WithoutLocalVar=pow(10, (round_off_digits * -1 ));

std::cout<<"withLocalVar: "<<withLocalVar<<" "<<"WithoutLocalVar :"<<WithoutLocalVar;

return WithoutLocalVar;
}

public:

inline static bool notequal(double a,double b)
{
double res=fabs(a-b);

if( res <= calcEpsilonValue())
{
return true;
}
else
{
return false;
}
return false;
}
};


int main()
{
FloatRelationalOperators<>::notequal(10.1,10.0);
}


I am trying to calculate the epsilon value from max round off digits.

When i run the program, i got the result as follows,

withLocalVar: 1e-10 WithoutLocalVar :inf


Why my answer is wrong when non-type template parameter is used directly in the function?

Am I doing anything wrong?

Answer

round_off_digits is an unsigned value and you multiply it with -1 which makes a pretty big unsigned int. If you change it to int it works

http://cpp.sh/8yflj