User Defined Literals in C++


Here we will see the concept of the user-defined literals in C++. From C++ version 11, the User Defined Literals (UDL) are added in C++. C++ also provides literals for a variety of built-in types but these are limited.

Built-in Literals −

  • 31 (Integer)

  • 3.5 (Double)

  • 4.2F (Float)

  • 'p' (Character)

  • 31ULL (Unsigned Long Long)

  • 0xD0 (Unsigned Hexadecimal Integer)

  • "pq" (String)

Apart from the built-in literals, sometimes we need user defined literals. There are few reasons behind that. Let us see with few examples −

Suppose we want to define one weight variable, but we cannot specify the units, like if we define as follows −

long double Weight = 3.5;

We have no idea about the unit, (pounds?, kilograms? grams?) but using UDL we can attach units with the values. There are few benefits, it makes more readable code and also supports conversion during compile time

weight = 5.6kg;
ratio = 5.6kg/2.1lb;

To find the above ratio it is required to convert them to same units. But UDLs helps us to overcome unit translation cost. In this case, we can define user-defined literals in case of userdefined types and new form of literals in case of built-in types. UDL’s cannot be able to save much of coding time but more and more calculations can be shifted to compile-time because of faster execution.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include<iostream>
#include<iomanip>
using namespace std;
unsigned long long int operator"" _kb( unsigned long long int x ) {
   return x*1024;
}
unsigned long long int operator"" _b( unsigned long long int x ) {
   return x;
}
unsigned long long int operator"" _mb( unsigned long long int x ) {
   return x * 1024 * 1024;
}
int main() {
   unsigned long long int size = 24_kb;
   cout << "Size:" << size << endl;
   cout << "Few more MB:" << ( size + 2_mb ) << endl;
   cout << "Size Div:" <<( 10_kb / 2_kb ) << endl;
   cout << "1KB = " <<( 8_b * 128_b ) << endl;
   return 0;
}

Output

Size:24576
Few more MB:2121728
Size Div:5
1KB = 1024

Updated on: 27-Aug-2020

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements