C++14 Features

In this post we discuss some of the key features added in C++14. In particular, we look at the following enhancements:

Language features:

  • Automatic return type deduction
  • Generic lambdas
  • Extended constexpr functionality

Standard library features:

  • std::make_unique
  • Additional user-defined literals

Language features

Automatic return type deduction

It is now possible for the compiler to deduce the return type from a function:

auto daysInYear(bool leap)
{
    if (leap)
        return 366;
    else
        return 365;
}

In the example above, the compiler will automatically deduce that the return type is int.

If the return types are not consistent, for example:

auto daysInYear(bool leap)
{
    if (leap)
        return 366.0;
    else
        return 365;
}

then the compiler will output an error message.

Generic lambdas

Prior to C++14, the parameter types in a lambda function needed to be defined explicitly. E.g.

std::vector<int> data = { 5, 7, 1 };
std::sort(data.begin(), data.end(), 
    [](int a, int b) {return a < b;});

In C++14, it is possible to declare the parameters as auto:

std::sort(data.begin(), data.end(), 
    [](auto a, auto b) {return a < b;});

Extended constexpr functionality

In C++11, the constexpr specifier was used to decorate functions which can be evaluated at compile time. However, the syntax that could be used in a constexpr function was very restrictive.

In C++14, it is possible to:

  • Declare local variables
  • Use conditional statements (if and switch)
  • Use loop statements (for, while, do-while)

Standard library features

std::make_unique

C++11 introduced the new smart pointers unique_ptr and shared_ptr.

The preferred way of initialising a shared pointer is with the make_shared<T> template function:

std::shared_ptr<MyClass> ptr = std::make_shared<MyClass>();

In C++11, there was no equivalent initialisation function for unique_ptr so they had to be initialised as follows:

std::unique_ptr<MyClass> ptr = std::unique_ptr<MyClass>(new MyClass());

C++14 adds the make_unique<T> function, which can be used as follows:

std::unique_ptr<MyClass> ptr = std::make_unique<MyClass>();

Additional user-defined literals

C++11 introduced user-defined literals. In C++14, several useful ‘user defined’ literals are defined in the standard library. Notable additions are literals for defining complex numbers and time durations.

For example, prior to C++14, a complex number might be initialised as follows:

std::complex<double> x(0.0, 1.0); 

In C++14, the same complex number (in this case ii) can be defined with the following syntax:

using namespace std::complex_literals;
auto x = 1i;