#include <cassert>
#include <iostream>
#include <cmath> // for std::abs
template<unsigned int DIM> class Test
{
private:
double abs_error = 1e-6;
double mData[DIM];
public:
double& operator[](int index)
{
// To check that the input index is a valid one
assert(index < DIM);
assert(index > -1);
// Condition that checks for values between 0 and 1 inclusive
if (mData[index] >= 0.0 && mData[index] <= 1.0)
{
return mData[index];
}
// Values less than zero
else if (std::abs(mData[index]) <= abs_error && mData[index] <= 0.0)
{
return mData[index] = 0;
}
// Values more than one
else if (mData[index] >= 1.0 && std::abs(mData[index] - 1.0) <= abs_error)
{
std::cout << "You used this condition." << std::endl;
return mData[index] = 1;
}
// For every other possible value
else
{
assert(0);
throw 42;
}
return mData[index];
}
};
int main()
{
Test<6> p;
p[0] = 0.5;
std::cout << "p[0]: " << p[0] << std::endl;
p[1] = -1e-7;
std::cout << "p[1]: " << p[1] << std::endl;
// Comment the following two lines and check the test statement
//p[2] = 1+1e-8;
//std::cout << "p[2]: " << p[2] << std::endl;
// This code tests the same condition as in Test.h for
// values more than one
bool foo = 1+1e-8 >= 1.0 && std::abs(1+1e-8 - 1.0) <= 1e-6;
std::cout << "foo (should return 1): " << foo << std::endl;
return 0;
}