Underscore in User-Defined Literals
Why must user-defined literals start with an underscore?
User-defined literals in C++ must start with an underscore (_
) to distinguish them from standard library literals and to ensure future compatibility. Here's why this rule is important:
Differentiation from Standard Literals
The underscore requirement ensures that user-defined literals are distinct from standard literals provided by the C++ standard library. For example, the standard library provides the "s"
suffix for std::string
literals:
#include <string>
using namespace std::string_literals;
std::string str = "Hello"s;
Without the underscore requirement, there could be a conflict between user-defined and standard literals, leading to ambiguity and potential errors in the code.
Future Compatibility
By mandating the underscore, the C++ standard reserves the possibility of adding new standard literals in future versions without breaking existing code.
If user-defined literals could omit the underscore, any new standard literals could conflict with existing user-defined ones, causing significant compatibility issues.
Example
Here's an example demonstrating the use of user-defined literals with an underscore:
#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)};
}
int main() {
Distance d = 5.0_meters;
std::cout << d;
}
5 meters
Standard Enforcement
Most modern compilers enforce this rule, but some older compilers or less compliant ones might not.
Even if your current compiler does not enforce the underscore, it's a good practice to follow the standard for the sake of portability and future-proofing your code.
Conclusion
Using an underscore in user-defined literals is a simple but important rule that helps maintain clear, unambiguous, and future-proof code.
It differentiates your custom literals from those provided by the standard library and ensures compatibility with future updates to the C++ standard.
User Defined Literals
A practical guide to user-defined literals in C++, which allow us to write more descriptive and expressive values