[c++] User-defined literals

In C++, literals are constants that are directly used in the program without any further computation. For example, 10 and 3.14 are literals representing the integer 10 and the floating point number 3.14, respectively.

C++ allows the creation of user-defined literals, which enable users to define their own custom suffixes for numeric literals. This feature was introduced in C++11 and is denoted by the use of underscore followed by the name of the user-defined literal.

Syntax for defining user-defined literals

The syntax for defining user-defined literals involves creating a function that takes in the literal value as an argument and returns the desired type. This function must be suffixed with the underscore and the name of the user-defined literal.

return_type operator "" _suffix (parameter);

Here, return_type specifies the type of the literal and parameter represents the literal value to be converted.

Example of user-defined literals

Let’s consider a simple example of defining a user-defined literal for converting a temperature in Celsius to Fahrenheit.

#include <iostream>

// User-defined literal for converting Celsius to Fahrenheit
long double operator "" _CelsiusToFahrenheit(long double celsius) {
    return celsius * 9.0 / 5.0 + 32;
}

int main() {
    // Using the user-defined literal to convert temperature
    long double tempF = 36.5_CelsiusToFahrenheit;
    std::cout << "Temperature in Fahrenheit: " << tempF << std::endl;
    
    return 0;
}

In this example, the _CelsiusToFahrenheit user-defined literal takes the temperature in Celsius as an argument and converts it to Fahrenheit using the specified formula.

Benefits of user-defined literals

User-defined literals provide a way to create custom representations of numeric values, enabling more expressive and intuitive code. They also enhance type safety by allowing specific types to be associated with literals.

Conclusion

User-defined literals in C++ offer a powerful mechanism for extending the language’s built-in literals to support custom types and operations. By defining custom suffixes for numeric literals, developers can enhance the expressiveness and usability of their code.

For more information, refer to the C++ documentation on user-defined literals.