Yes, user-defined literals in C++ can be overloaded to handle different types of input. This allows you to create more versatile and expressive literals. Here’s how you can do it:
You can overload user-defined literals by defining multiple functions with different parameter types. The C++ standard supports the following parameter types for literals:
unsigned long long
for integerslong double
for floating-point numbersconst char*
for stringschar
for charactersHere’s an example of overloading user-defined literals for distance conversions:
#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""_meters(unsigned long long val) {
return Distance{static_cast<float>(val)};
}
Distance operator""_kilometers(long double val) {
return Distance{static_cast<float>(val * 1000)};
}
Distance operator""_kilometers(unsigned long long val) {
return Distance{static_cast<float>(val * 1000)};
}
int main() {
Distance d1 = 3.0_kilometers;
Distance d2 = 1500_meters;
std::cout << d1;
std::cout << d2;
}
3000 meters
1500 meters
Here’s another example demonstrating overloading with string and number literals:
#include <iostream>
#include <string>
std::string operator""_name(
const char* str, size_t) {
return std::string(str);
}
int operator""_age(unsigned long long val) {
return static_cast<int>(val);
}
int main() {
std::string playerName = "Legolas"_name;
int playerAge = 2931_age;
std::cout << "Player: " << playerName
<< ", Age: " << playerAge;
}
Player: Legolas, Age: 2931
Overloading user-defined literals can enhance the expressiveness and versatility of your code. By following best practices and thoroughly testing your literals, you can create a powerful and intuitive API for your projects.
Answers to questions are automatically generated and may not have been reviewed.
A practical guide to user-defined literals in C++, which allow us to write more descriptive and expressive values