User Defined Literals

Custom Types and User-Defined Literals

Can user-defined literals be used with custom types?

Abstract art representing computer programming

Yes, user-defined literals can indeed be used with custom types in C++. This allows us to create more expressive and meaningful code. Let's see how this works with an example.

Suppose we have a Distance class that we want to use with user-defined literals to represent various units of distance. Here’s a simple implementation:

#include <iostream>

class Distance {
 public:
  Distance(float value) : value{value} {}
  float value;
};

std::ostream& operator<<(
  std::ostream& os, Distance d) {
  os << d.value << " meters\n";
  return os;
}

Distance operator""_meters(long double val) {
  return Distance{static_cast<float>(val)};
}

Distance operator""_kilometers(long double val) {
  return Distance{static_cast<float>(val * 1000)};
}

Distance operator""_miles(long double val) {
  return Distance{static_cast<float>(
    val * 1609.34
  )};
}

int main() {
  Distance d1 = 5.0_kilometers;
  Distance d2 = 2.5_miles;

  std::cout << d1;
  std::cout << d2;
}
5000 meters
4023.35 meters

In this example, we've defined three user-defined literals: _meters, _kilometers, and _miles. Each of these literals converts a numeric value to a Distance object.

Here's a breakdown of what happens:

  • 5.0_kilometers calls the operator""_kilometers function, which returns a Distance object with the value converted to meters.
  • 2.5_miles calls the operator""_miles function, similarly converting the value to meters.

The std::ostream& operator<< overload allows us to print Distance objects directly using std::cout.

Using user-defined literals with custom types like this enhances code readability and makes it clear what units are being used, reducing the chance for errors and making the code more maintainable.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved