User Defined Literals in C++

This tutorial will teach you about the User Defined Literals in C++. We can use UDLs in C++ to define our own literal values. Let’s have a detailed discussion over UDLs further in this tutorial.

User-Defined Literals in C++

Before directly trying to understand how we can use user-defined literals in our program, let’s first understand why we need them.

Why do we need UDLs?

Let’s consider an example. We want to measure the length of something. Now as we know that the length can have different units and the user can use any of those units for his inputs. In such cases, UDLs are more appropriate to use for our calculation. There are a few advantages to using UDLs. Those are listed here.

  • The value of UDLs is substituted with actual value as given in the code at the compile-time resulting into faster execution of our program.
  • Using User-defined Literals makes our code more readable.
  • They can be used with user-defined types and as well as built-in types.

Example program to illustrate User-Defined Literals 

#include <iostream>
using namespace std;

//user defined literals

//Kilometer
long double operator"" _km (long double length)
{
  return length*1000;
}

//Meter
long double operator"" _m (long double length)
{
  return length;
}

//Millimeter
long double operator"" _mm (long double length)
{
  return length/1000;
}

int main()
{
  long double dist = 4.0_km;
  cout << "4 km = " << dist << " meter";
  cout << "\n4 km/1000 m = " << (4.0_km / 1000.0_m);
  cout << "\n4 km + 1000 mm = " << (4.0_km + 1000.0_mm) << " meter";
  cout << "\n4000 mm * 100 m = " << (4000.0_mm * 100.0_m) << " meter^2" << endl;
  
  return 0;
}

And the output is:

4 km = 4000 meter
4 km/1000 m = 4
4 km + 1000 mm = 4001 meter
4000 mm * 100 m = 400 meter^2

As you can see in the program, we have defined three user-defined literals km(kilometer), m(meter), mm(millimeter). Note that there is a space between operator”” and _km and similarly other literals. Also, you can understand by looking at the output that using UDLs helps us avoid many conversion codes that we might have to write if we had not used it.

Thank you.

Also, read: Data Types in C++ and How To Define A Struct in C++

Leave a Reply

Your email address will not be published. Required fields are marked *