User Defined Literals in C++
Level 5563 keystrokes
User-defined literals let a suffix build an object: 500.0_m and 2.5_km both create Distance values stored in meters. They are added with operator+, and the total of 3000 m (3 km) is printed.
C++ code
1class Distance { // The distance is always stored in meters2 double meters;3public: // explicit: a bare double does not become a Distance by accident4 explicit Distance(double m) : meters(m) {}5 double getMeters() const { return meters; } // Converts meters to kilometers6 double getKilometers() const { return meters / 1000.0; } // Adding two distances gives a new Distance7 Distance operator+(const Distance& other) const { return Distance(meters + other.meters); }8};9 // Literal operator for the _m suffix; floating literals arrive as long double10Distance operator""_m(long double m) { return Distance(m); }// _km converts kilometers to meters11Distance operator""_km(long double km) { return Distance(km * 1000); }12 // Calls operator""_m(500.0): 500 m13auto d1 = 500.0_m;// 2.5 km is stored as 2500 m14auto d2 = 2.5_km;// 500 + 2500 = 3000 m15auto total = d1 + d2;16 // Prints "Total: 3000m (3km)"17cout << "Total: " << total.getMeters() << "m (" << total.getKilometers() << "km)" << endl;Output
Total: 3000m (3km)
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
(× 13)× 13<× 12;× 11"× 10{× 7}× 7.× 6_× 4:× 3