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 meters
2 double meters;
3public:
// explicit: a bare double does not become a Distance by accident
4 explicit Distance(double m) : meters(m) {}
5 double getMeters() const { return meters; }
// Converts meters to kilometers
6 double getKilometers() const { return meters / 1000.0; }
// Adding two distances gives a new Distance
7 Distance operator+(const Distance& other) const { return Distance(meters + other.meters); }
8};
9
// Literal operator for the _m suffix; floating literals arrive as long double
10Distance operator""_m(long double m) { return Distance(m); }
// _km converts kilometers to meters
11Distance operator""_km(long double km) { return Distance(km * 1000); }
12
// Calls operator""_m(500.0): 500 m
13auto d1 = 500.0_m;
// 2.5 km is stored as 2500 m
14auto d2 = 2.5_km;
// 500 + 2500 = 3000 m
15auto 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

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

More C++ examples at level 5

← C++ typing practice