User Defined Literals

# 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.

This Question is from the Lesson:

### User Defined Literals

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

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

This Question is from the Lesson:

### User Defined Literals

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

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.