User Defined Literals in C++
Last Updated :
30 Jun, 2023
A literal is used for representing a fixed value in a program. A literal could be anything in a code like a, b, c2. , ‘ACB’, etc.
Similarly, User-Defined Literals (UDL) provides literals for a variety of built-in types that are limited to integer, character, floating-point, string, boolean, and pointer. In simple terms, they combine values with units.
Examples of literal for built-in types:
// Examples of classical literals for built-in types.
42 // int
2.4 // double
3.2F // float
'w' // char
32ULL // Unsigned long long
0xD0 // Hexadecimal unsigned
"cd" // C-style string(const char[3]")
Why do we use UDLs?
Let us consider the below example to understand the need for UDLs.
long double Weight = 2.3; // pounds? kilograms? grams?
// With UDL, we attach units to the values which has
// following advantages
// 1) The code becomes readable.
// 2) Conversion computations are done at compile time.
weight = 2.3kg;
ratio = 2.3kg/1.2lb;
To compute the above ratio it is necessary to convert them to the same units. UDLs help us to overcome unit translation costs. We can define user-defined literals for user-defined types and the new form of literals for built-in types. They help to make constants in code more readable. The value of UDLs is substituted with the actual value defined in the code by the compiler at compile time. UDLs don’t save much coding time, but more calculations can be shifted to compile-time for faster execution.
Examples of User-Defined Literals:
"hello"s // string
4.3i // imaginary
101000111101001b // binary
53h // hours
234093270497230409328432840923849 // extended-precision
UDLs are treated as a call to a literal operator. Only suffix form is supported. The name of the literal operator is operator ” “ followed by the suffix.
Example 1:
CPP
#include <iomanip>
#include <iostream>
using namespace std;
long double operator"" _kg(long double x)
{
return x * 1000;
}
long double operator"" _g(long double x) { return x; }
long double operator"" _mg(long double x)
{
return x / 1000;
}
int main()
{
long double weight = 3.6_kg;
cout << weight << endl;
cout << setprecision(8) << (weight + 2.3_mg) << endl;
cout << (32.3_kg / 2.0_g) << endl;
cout << (32.3_mg * 2.0_g) << endl;
return 0;
}
|
Output
3600
3600.0023
16150
0.0646
Example 2:
CPP
#include <complex>
#include <iostream>
using namespace std;
constexpr complex<double> operator"" _i(long double d)
{
return complex<double>{ 0.0, static_cast<double>(d) };
}
int main()
{
complex<double> z = 3.0 + 4.0_i;
complex<double> y = 2.3 + 5.0_i;
cout << "z + y = " << z + y << endl;
cout << "z * y = " << z * y << endl;
cout << "abs(z) = " << abs(z) << endl;
return 0;
}
|
Output
z + y = (5.3,9)
z * y = (-13.1,24.2)
abs(z) = 5
What is an imaginary literal?
The literal complex<double> is the real part that deals with the imaginary part your_argument
Syntax:
constexpr complex< double > operator"" _i( long double your_argument );
your_argument – the value of the imaginary number. Here, constexpr is used to enable compile-time evaluation.
Restriction: UDL can only work with the following parameters:
char const*
unsigned long long
long double
char const*, std::size_t
wchar_t const*, std::size_t
char16_t const*, std::size_t
char32_t const*, std::size_t
But return value can be of any type.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Similar Reads
User Defined Literals in C++
A literal is used for representing a fixed value in a program. A literal could be anything in a code like a, b, c2. , 'ACB', etc. Similarly, User-Defined Literals (UDL) provides literals for a variety of built-in types that are limited to integer, character, floating-point, string, boolean, and poin
3 min read
User Defined Data Types in C++
User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types: Table of Content ClassStruc
4 min read
Literals in C++
In C++ programming language, literals are fundamental elements used to represent fixed values. These values can include numbers, characters, strings, and more. They are generally present as the right operand in the assignment operation. Let's take a look at an example: [GFGTABS] C++ #include <ios
6 min read
Smart Pointers in C++
Prerequisite: Pointers in C++ Pointers are used for accessing the resources which are external to the program - like heap memory. So, for accessing the heap memory (if anything is created inside heap memory), pointers are used. When accessing any external resource we just use a copy of the resource.
8 min read
Raw String Literal in C++
A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ' \n, \t, or \" ' of C++ are not processed. Hence, a raw string literal that starts with R"( and ends in )". The syntax for R
2 min read
#define in C++
In C++, #define is a preprocessor directive used to define a macro. Macros are a way to represent a fragment of code or a constant value by giving it a name. When the preprocessor encounters the macro name in the code, it replaces it with the corresponding code fragment or value that is defined usin
4 min read
Multi-Character Literal in C/C++
Character literals for C and C++ are char, string, and their Unicode and Raw type. Also, there is a multi-character literal that contains more than one c-char. A single c-char literal has type char and a multi-character literal is conditionally-supported, has type int, and has an implementation-defi
6 min read
âstatic constâ vs â#defineâ vs âenumâ
In this article, we will be analyzing "static const", "#define" and "enum". These three are often confusing and choosing which one to use can sometimes be a difficult task. static const static const : "static const" is basically a combination of static(a storage specifier) and const(a type qualifier
4 min read
Derived Data Types in C++
The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality. In C++, there are four different derived data types: Table of Co
4 min read
C++ Vector of Pointers
Prerequisites Pointers in C++Vectors in C++ Vector of pointers are vectors that can hold multiple pointers. Each pointer within a vector of pointers points to an address storing a value. We can use the vector of pointers to manage values that are not stored in continuous memory. How to Create Vector
6 min read