Skip to content

Commit

Permalink
Support negative exponent in power_of_unit (#227)
Browse files Browse the repository at this point in the history
* Update units.h

* Update main.cpp

* fix typo

Co-authored-by: Nic Holthaus <[email protected]>
  • Loading branch information
OpportunityLiu and nholthaus authored Oct 10, 2020
1 parent 1e2c7ed commit ea6d126
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
18 changes: 17 additions & 1 deletion include/units.h
Original file line number Diff line number Diff line change
Expand Up @@ -2756,14 +2756,30 @@ namespace units
/// recursive exponential implementation
template <int N, class U> struct power_of_unit
{
typedef typename units::detail::unit_multiply<U, typename power_of_unit<N - 1, U>::type> type;
template<bool isPos, int V> struct power_of_unit_impl;

template<int V> struct power_of_unit_impl<true, V>
{
typedef units::detail::unit_multiply<U, typename power_of_unit<N - 1, U>::type> type;
};

template<int V> struct power_of_unit_impl<false, V>
{
typedef units::inverse<typename power_of_unit<-N, U>::type> type;
};

typedef typename power_of_unit_impl<(N > 0), N>::type type;
};

/// End recursion
template <class U> struct power_of_unit<1, U>
{
typedef U type;
};
template <class U> struct power_of_unit<0, U>
{
typedef units::dimensionless::dimensionless type;
};
}
/** @endcond */ // END DOXYGEN IGNORE

Expand Down
15 changes: 15 additions & 0 deletions unitTests/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2817,6 +2817,21 @@ TEST_F(UnitMath, pow)
bool isSame;
meter_t value(10.0);

auto inv_sq = pow<-2>(value);
EXPECT_NEAR(0.01, inv_sq(), 5.0e-5);
isSame = std::is_same<decltype(inv_sq), unit_t<inverse<square_meter>>>::value;
EXPECT_TRUE(isSame);

auto inv = pow<-1>(value);
EXPECT_NEAR(0.1, inv(), 5.0e-4);
isSame = std::is_same<decltype(inv), unit_t<inverse<meter>>>::value;
EXPECT_TRUE(isSame);

auto scalar = pow<0>(value);
EXPECT_NEAR(1, scalar(), 5.0e-3);
isSame = std::is_same<decltype(scalar), scalar_t>::value;
EXPECT_TRUE(isSame);

auto sq = pow<2>(value);
EXPECT_NEAR(100.0, sq(), 5.0e-2);
isSame = std::is_same<decltype(sq), square_meter_t>::value;
Expand Down

0 comments on commit ea6d126

Please sign in to comment.