0

I would like to overload user defined literals so that it will allow to perform some physical calculations, e.g

auto force = 5_N;         // force in newton
auto distance = 6.8_m;    // distance in meters

auto resultingEnergy = force * distance;    // expected result in joules

How can it be achieved ?

tommyk
  • 3,187
  • 7
  • 39
  • 61
  • 2
    You'd need strong typedefs for values (or just new types) and overloaded operators. Literals only produce values of some given type, being a syntax sugar. – Bartek Banachewicz Oct 03 '14 at 13:11
  • 2
    You can look at [Boost.Units](http://www.boost.org/doc/libs/1_56_0/doc/html/boost_units.html) for inspiration, and basically make user-defined literals return the appropriate Boost.Units types. – Angew is no longer proud of SO Oct 03 '14 at 13:14

1 Answers1

1

You can define some new types (or use boost units as mentioned above),

A user defined solution could be similar to:

#define DECLARE_UNIT(UnitName) \
struct UnitName { \
    UnitName(const long double val) noexcept : val_(val) {};\
    long double val_ = 0.0; \
};

DECLARE_UNIT(Joule);
DECLARE_UNIT(Newton);
DECLARE_UNIT(Meters);

const Newton operator""_N(const long double n) noexcept {
    return Newton(n);
}
const Meters operator""_m(const long double m) noexcept {
    return Meters(m);
}

const Joule operator*(const Newton& newtons, const Meters& meters) noexcept {
    return newtons.val_ * meters.val_;
}


int main() {
    auto force = 5.0_N;
    auto distance = 6.8_m;
    auto energy = force * distance; // of Joule type
}
Danny Shemesh
  • 67
  • 1
  • 9