LearnFrenzy
Sign in Take a free test

Abstraction · Abstraction Programs · Question 9

Unit-safe distance and speed types in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Create strong types Km and Hours with explicit constructors and an operator/ that returns a Kmph type; compute trip speeds and make wrong combinations impossible to compile.

Solution
main.cpp
#include <format>
#include <iostream>

struct Km    { double v; explicit constexpr Km(double x) : v(x) {} };
struct Hours { double v; explicit constexpr Hours(double x) : v(x) {} };
struct Kmph  { double v; explicit constexpr Kmph(double x) : v(x) {} };

constexpr Km operator+(Km a, Km b) { return Km(a.v + b.v); }
constexpr Hours operator+(Hours a, Hours b) { return Hours(a.v + b.v); }
constexpr Kmph operator/(Km d, Hours t) { return Kmph(d.v / t.v); }
constexpr Km operator*(Kmph s, Hours t) { return Km(s.v * t.v); }

int main() {
    Km leg1(120), leg2(180);
    Hours t1(2), t2(2.5);
    Kmph avg = (leg1 + leg2) / (t1 + t2);
    Km next = Kmph(80) * Hours(1.5);
    std::cout << std::format("average {:.2f} km/h, next leg {} km\n", avg.v, next.v);
    // Km bad = leg1 / leg2;        error: no operator/(Km, Km) returning Km
    // Kmph wrong = t1 / leg1;      error: no operator/(Hours, Km)
    static_assert(sizeof(Km) == sizeof(double));
    return 0;
}

Output Verified by compiling and running

average 66.67 km/h, next leg 120 km

The types carry meaning, only physically valid operations exist, and static_assert confirms there is no space overhead.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links