User Defined Literals

Underscore in User-Defined Literals

Why must user-defined literals start with an underscore?

Abstract art representing computer programming

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.

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