Skip to content

Commit

Permalink
hide number operator overloads in a namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
SizzinSeal committed Jan 7, 2025
1 parent 8902c87 commit 550edc1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
8 changes: 8 additions & 0 deletions include/units/units.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -363,31 +363,38 @@ constexpr inline double to_num(Number quantity) { return quantity.internal(); }
constexpr bool operator op(Number lhs, double rhs) { return (lhs.internal() op rhs); } \
constexpr bool operator op(double lhs, Number rhs) { return (lhs op rhs.internal()); }

namespace units_double_ops {
NEW_NUM_TO_DOUBLE_COMPARISON(==)
NEW_NUM_TO_DOUBLE_COMPARISON(!=)
NEW_NUM_TO_DOUBLE_COMPARISON(<=)
NEW_NUM_TO_DOUBLE_COMPARISON(>=)
NEW_NUM_TO_DOUBLE_COMPARISON(<)
NEW_NUM_TO_DOUBLE_COMPARISON(>)
} // namespace units_double_ops

#define NEW_NUM_AND_DOUBLE_OPERATION(op) \
constexpr Number operator op(Number lhs, double rhs) { return (lhs.internal() op rhs); } \
constexpr Number operator op(double lhs, Number rhs) { return (lhs op rhs.internal()); }

namespace units_double_ops {
NEW_NUM_AND_DOUBLE_OPERATION(+)
NEW_NUM_AND_DOUBLE_OPERATION(-)
NEW_NUM_AND_DOUBLE_OPERATION(*)
NEW_NUM_AND_DOUBLE_OPERATION(/)
} // namespace units_double_ops

#define NEW_NUM_AND_DOUBLE_ASSIGNMENT(op) \
constexpr void operator op##=(Number& lhs, double rhs) { lhs = lhs.internal() op rhs; } \
constexpr void operator op##=(double& lhs, Number rhs) { lhs = lhs op rhs.internal(); }

namespace units_double_ops {
NEW_NUM_AND_DOUBLE_ASSIGNMENT(+)
NEW_NUM_AND_DOUBLE_ASSIGNMENT(-)
NEW_NUM_AND_DOUBLE_ASSIGNMENT(*)
NEW_NUM_AND_DOUBLE_ASSIGNMENT(/)
} // namespace units_double_ops

namespace units_double_ops {
constexpr Number& operator++(Number& lhs, int) {
lhs += 1;
return lhs;
Expand All @@ -409,6 +416,7 @@ constexpr Number operator--(Number& lhs) {
lhs -= 1;
return copy;
}
} // namespace units_double_ops

NEW_UNIT_LITERAL(Number, percent, num / 100)

Expand Down
3 changes: 3 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ constexpr void angleRangeTests() {
}

constexpr Number numAssignmentTests() {
using namespace units_double_ops;
Number n = 1_num; // 1
n += 2; // 3
n--; // 2
Expand All @@ -71,6 +72,7 @@ constexpr Number numAssignmentTests() {
}

constexpr double doubleAssignmentTests() {
using namespace units_double_ops;
double d = 1; // 1
d += 2_num; // 3
d -= 2_num; // 1
Expand All @@ -80,6 +82,7 @@ constexpr double doubleAssignmentTests() {
}

void numberOperatorTests() {
using namespace units_double_ops;
static_assert(1_num + 2 == 3);
static_assert(1 + 2_num <= 3);
static_assert(1 / 2_num >= 0);
Expand Down

0 comments on commit 550edc1

Please sign in to comment.