Skip to content

Commit

Permalink
Add support for comparison of Approx with strong typedefs
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Coe authored and jbcoe committed Oct 4, 2016
1 parent 88732e8 commit 0f098bd
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
17 changes: 17 additions & 0 deletions include/internal/catch_approx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
#include <cmath>
#include <limits>

#if defined(__cplusplus) && __cplusplus >= 201103L
#include <type_traits>
#endif

namespace Catch {
namespace Detail {

Expand Down Expand Up @@ -40,7 +44,19 @@ namespace Detail {
approx.scale( m_scale );
return approx;
}
#if defined(__cplusplus) && __cplusplus >= 201103L
template <typename T, typename = typename std::enable_if<std::is_constructible<T, double>::value>::type>
friend bool operator == ( const T& lhs, Approx const& rhs ) {
// Thanks to Richard Harris for his help refining this formula
auto lhs_v = (double)lhs;
return fabs( lhs_v - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs_v), fabs(rhs.m_value) ) );
}

template <typename T, typename = typename std::enable_if<std::is_constructible<T, double>::value>::type>
friend bool operator == ( Approx const& lhs, const T& rhs ) {
return operator==( rhs, lhs );
}
#else // defined(__cplusplus) && __cplusplus >= 201103L
friend bool operator == ( double lhs, Approx const& rhs ) {
// Thanks to Richard Harris for his help refining this formula
return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) );
Expand All @@ -49,6 +65,7 @@ namespace Detail {
friend bool operator == ( Approx const& lhs, double rhs ) {
return operator==( rhs, lhs );
}
#endif // defined(__cplusplus) && __cplusplus >= 201103L

friend bool operator != ( double lhs, Approx const& rhs ) {
return !operator==( lhs, rhs );
Expand Down
26 changes: 26 additions & 0 deletions projects/SelfTest/ApproxTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,29 @@ TEST_CASE( "Approximate PI", "[Approx][PI]" )
REQUIRE( divide( 22, 7 ) == Approx( 3.141 ).epsilon( 0.001 ) );
REQUIRE( divide( 22, 7 ) != Approx( 3.141 ).epsilon( 0.0001 ) );
}

////////////////////////////////////////////////////////////////////////////////

#if defined(__cplusplus) && __cplusplus >= 201103L
class StrongDoubleTypedef
{
double d_ = 0.0;

public:
explicit StrongDoubleTypedef(double d) : d_(d) {}
explicit operator double() const { return d_; }
};

TEST_CASE
(
"Comparison with explicitly convertible types",
"[Approx]"
)
{
StrongDoubleTypedef td(10.0);

REQUIRE(td == Approx(10.0));
}
#endif // defined(__cplusplus) && __cplusplus >= 201103L

////////////////////////////////////////////////////////////////////////////////

0 comments on commit 0f098bd

Please sign in to comment.