C++ 14 – Literals

C++ 14 has introduced new features for literals. We will see each of them using a sample C++ example program. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/literals.cpp.

These are the header files in the program.

#include <iostream>
#include <complex>
#include <thread>
#include <chrono>

int main() {

Binary literals can be directly kept using 0b as a prefix and easily be known as binary for people reading the program.

    // Binary literals
    int binary_literal = 0b101010;
    std::cout << "Binary literal: " << binary_literal << std::endl;

Separators can be used between digits, as shown. It is beneficial for large numbers.

    // Digit separators
    int large_number = 1'234'567;
    std::cout << "Large number with digit separators: " << large_number << std::endl;

You can use Chrono literals. For example, you can use ms for the time-related variables.

    // Standard user-defined literals for time
    using namespace std::literals::chrono_literals;
    auto duration = 500ms;
    std::cout << "Duration: " << duration.count() << " milliseconds" << std::endl;

You can write complex numbers in a format such as 3.0 + 4.0i from C++ 14 onwards.

    // Standard user-defined literals for complex numbers
    using namespace std::literals::complex_literals;
    auto complex_number = 3.0 + 4.0i;
    std::cout << "Complex number: " << complex_number << std::endl;

You can use std::this_thread::sleep for a thread to sleep for a particular duration.

    // Sleep for the duration using std::this_thread::sleep_for
    std::cout << "Sleeping for " << duration.count() << " milliseconds..." << std::endl;
    std::this_thread::sleep_for(duration);
    std::cout << "After sleep!" << std::endl;

    return 0;
}

The compilation and output of the program are as shown.

$ g++ -std=c++14 literals.cpp -o literals
$ ./literals 
Binary literal: 42
Large number with digit separators: 1234567
Duration: 500 milliseconds
Complex number: (3,4)
Sleeping for 500 milliseconds...
After sleep!