×

User-defined literals in C++

Introduction to User-Defined Literals:

User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes can be used to create instances of user-defined types, such as custom classes or enumerations. They can also create instances of built-in types with specific values or formats.

User-defined literals are defined using special suffixes added to the end of a literal value. For example, a developer might define a UDL to represent a length in meters by using the suffix "m" at the end of a numeric value. This would allow them to write code like "5m" instead of "5 * meters" to represent a length of 5 meters.

To define a UDL, a developer must use a special operator called a literal operator, a function that takes a single argument and returns a value of a specific type. The literal operator's name is formed by prefixing the suffix with the keyword operator. So, for example, in the first example, the operator would be called operator""m.

User-defined literals with Built-in Type:

A user-defined literal with a built-in type is a way to define a new literal for a built-in data type, such as int or double, in C++.

This is done by overloading the operator "" (double quotes) and specifying the type of the literal in the function name.

For example, to define a new literal for int, the operator "" _int() could be defined. This would allow the user to create an int variable using the new literal, such as int x = 12_int;

Consider the following code:

#include<iostream>


long double operator"" _degrees(long double v) {
    return v * 3.14159265358979323846 / 180.0;
}


int main() {
    double x = 90.0_degrees;
    std::cout << x << std::endl;
    return 0;
}

Explanation:

  • This code defines a user-defined literal operator, which is a special type of function that can be used to create custom syntax for a program.
  • The operator is defined using the "operator"" _degrees" syntax, where "operator"" _degrees" is the name of the operator, and "long double" is the return type. The operator takes a single argument, "v", which is the value in degrees that the operator will convert to radians.
  • The operator itself performs the conversion by multiplying the value "v" by the constant value of pi divided by 180. This is the conversion factor between degrees and radians.
  • In the main function, the code declares a variable "x" and assigns it the value of 90 degrees in radians by using the "_degrees" suffix after the value 90.0. The "_degrees" is the suffix which we defined in our user-defined operator.
  • Finally, the program uses the "std::cout" function to print the value of x to the console. This will output the value of pi/2 (90 degrees in radians).

Program Output:

User-defined literals

User-defined literals with custom class:

A user-defined literal allows you to define a new literal operator for use with a custom class. This allows us to create objects of our custom class using a syntax that is similar to the syntax used for built-in types.

To define a user-defined literal for a custom class, you need to define a function that takes a string or a character array as its parameter and returns an object of the custom class. This function should be preceded by the keyword "operator" and the literal operator you want to define.

For example, consider the following code:

#include<iostream>
#include<iomanip>
class MyType {
public:
    int value;
    MyType(int v) : value(v) {}
};


MyType operator"" _mytype(unsigned long long v) {
    return MyType(v);
}


int main() {
    MyType x = 10_mytype;
    std::cout << x.value << std::endl;
    return 0;
}

Explanation:

  • The program defines a simple class called MyType, which has a single public member variable called "value" of type int. The class also has a constructor that takes an int argument and initializes the value variable with that argument.
  • The program also defines a user-defined literal operator overload using the "operator"" _" syntax. This operator overload is a function called "operator"" _mytype", which takes an unsigned long long argument and returns an object of type MyType.
  • The operator overload creates a new MyType object and initializes its value variable with the argument passed to the operator.
  • In the main function, we can see an example of using the user-defined literal. A variable x of type MyType is created and assigned the value 10, followed by the suffix _mytype. This is interpreted by the compiler as a call to the operator overload function, passing the value 10 as the argument.
  • The operator overload function creates a new MyType object and initializes its value variable with 10, and this object is then assigned to the variable x.
  • Finally, the program uses the standard cout to print the value of x, which is 10, the value passed to the operator overload.

Program Output:

User-defined literals

User-defined literals with String Literal:

User-defined literals provide a powerful way to extend the functionality of the C++ language and make it more expressive and user-friendly.

They can be used to create custom classes, enumerations, and built-in types with specific values or formats.

They can also be used to create custom units of measurement, custom date-time formats, custom formatting of numbers, and custom enumerations.

They provide a more natural and intuitive way of expressing values or formats in the code and make the code more expressive, readable, and less error-prone.

Additionally, User-defined literals are widely used in libraries and frameworks to provide a more convenient and expressive API for developers. They also have the ability to create literal operators for string literals, allowing developers to create more expressive and readable string manipulation code.

Consider the following code:

Program 1:

#include<iostream>
#include<string>
std::string operator"" _str(const char* str, std::size_t len)
{
    return std::string(str, len);
}


int main() {
    auto x = "hello"_str;
    std::cout << x << std::endl;
    return 0;
}

Explanation:

  • This code defines a user-defined literal operator, which allows a programmer to use a custom suffix (in this case, "_str") to indicate a string is to be treated as a std::string.
  • The operator takes two parameters, a pointer to a constant char, "str", and a std::size_t, "len".
  • The operator converts the string to a std::string by using the std::string constructor, which takes two arguments, a pointer to a char and a size_t, representing the start and the length of the string.
  • In the main function, the code declares a variable "x" and assigns it the value of "hello" by using the "_str" suffix after the string "hello". The "_str" is the suffix which we defined in our user-defined operator.
  • Finally, the program uses the "std::cout" function to print the value of x to the console. This will output the value of "hello".

Program Output:

User-defined literals

Program 2:

#include <iostream>


class Length {
public:
    double value;
    Length(double v) : value(v) {}
};


Length operator"" _m(long double v) {
    return Length(v);
}
Length operator"" _cm(long double v) {
    return Length(v/100);
}
Length operator"" _mm(long double v) {
    return Length(v/1000);
}


int main() {
    Length x = 10.5_m;
    Length y = 1050.0_cm;
    Length z = 1050000.0_mm;
    std::cout << x.value << "m" << std::endl;
    std::cout << y.value << "m" << std::endl;
    std::cout << z.value << "m" << std::endl;
    return 0;
}

Explanation:

  • This program defines a C++ class called "Length", which has a single member variable "value" of type double.
  • It also defines three operator overloads for the class: "operator"" _m", "operator"" _cm", and "operator"" _mm".
  • These operators allow the user to create Length objects by appending the unit of measurement (meters, centimeters, or millimeters) as a suffix to a number.
  • In the main function, it creates three Length objects: x, y, and z.
  • The first object, x, is created by appending "_m" to the number 10.5, which is equivalent to calling the operator "" _m(10.5) and passing the resulting object to the constructor of class Length.
  • The second object, y, is created by appending "_cm" to the number 1050, which is equivalent to calling the operator "" _cm(1050) and passing the resulting object to the constructor of class Length.
  • The third object, z, is created by appending "_mm" to the number 1050000, which is equivalent to calling the operator "" _mm(1050000) and passing the resulting object to the constructor of class Length.
  • Finally, the program prints out the value of each object x, y, and z, followed by the unit of measurement "m" (for meters).
  • The first line is the value of variable x, which is initialized to 10.5_m. The operator "" _m converts the value 10.5 to a Length object with the value of 10.5.
  • The second line is the value of variable y, which is initialized to 1050_cm. The operator "" _cm converts the value 1050 to a Length object with the value of 10.5 (1050 / 100 = 10.5).
  • The third line is the value of variable z, which is initialized to 1050000_mm. The operator "" _mm converts the value 1050000 to a Length object with the value of 1050 (1050000 / 1000 = 1050).

This example demonstrates how user-defined literals can be used to create a custom measurement unit type that is more expressive and readable than using built-in types and conversion functions.

Program Output:

User-defined literals

Conclusion:

  • In conclusion, user-defined literals are a powerful feature in C++11 that allow developers to create custom syntax for their programs.
  • They make code more readable and expressive by allowing developers to create custom operators with meaning specific to their domain.
  •  User-defined literals can be used for various types, such as converting angles from degrees to radians, converting C-style strings to std::string, or for any other use case that requires a custom syntax. T
  • hey are easy to define and use and can greatly improve the readability of your code.

Related Topics

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

C++ OOPs Concept

The main goal of C ++ programming is to add the idea of ​​object orientation to the C programming language. Inheritance, data binding, polymorphism and other concepts are part of...

4 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

C++ vardiac() function

In the C++ programming language, the flexibility feature is provided by the variadic function. To understand more about flexibility, let's see the following syntax. Syntax: If we have to add two numbers,...

3 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.