Custom Types and User-Defined Literals

Can user-defined literals be used with custom types?

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.

User Defined Literals

A practical guide to user-defined literals in C++, which allow us to write more descriptive and expressive values

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Portability of User-Defined Literals
How can we ensure that our user-defined literals are portable across different compilers?
Underscore in User-Defined Literals
Why must user-defined literals start with an underscore?
Namespaces for User-Defined Literals
How do user-defined literals interact with namespaces?
Best Practices for User-Defined Literals
What are the best practices for using user-defined literals in large projects?
Overloading User-Defined Literals
Can user-defined literals be overloaded?
Negative Values in User-Defined Literals
How do we handle negative values in user-defined literals?
User-Defined Literals and Template Classes
How do user-defined literals work with template classes?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant