In C++, user-defined literals enable developers to define their own custom suffixes for literal constants. This enables the creation of convenient and expressive syntax for initializing values of user-defined types. User-defined literals can be defined for integer, floating-point, character, and string literals.
Syntax
To define a user-defined literal, the following syntax is used:
return_type operator"" suffix_name (parameter_type value);
The operator""
is a special operator that indicates a user-defined literal. suffix_name
is the custom suffix that will be used, and parameter_type
is the type of the literal passed to the user-defined literal. The return_type
can be any valid C++ type.
Example
Suppose we have a class called Distance
which represents a distance value and we want to define a user-defined literal to convert meters to Distance
objects. The user-defined literal can be defined as follows:
class Distance {
// class implementation
};
Distance operator"" _m(long double value) {
return Distance(value);
}
In this example, operator"" _m
is the user-defined literal for meters. It takes a long double
parameter, representing the value in meters, and returns a Distance
object.
After defining this user-defined literal, we can create Distance
objects using the custom suffix as follows:
auto d = 10.5_m; // creates a Distance object representing 10.5 meters
Restrictions
- User-defined literals must begin with an underscore
_
followed by lowercase letters, e.g.,_m
,_km
, etc. - User-defined literals cannot be defined for built-in types like
int
ordouble
. - User-defined literals cannot have default arguments.
User-defined literals provide a powerful mechanism for creating more expressive and readable code. They enable the customization of literal constants for user-defined types, ultimately leading to more natural and intuitive syntax.
For more details on user-defined literals, please refer to the C++ Standard.