DEV Community


Posted on

What is new in C++20?

C++20 is the latest version of the C++ programming language, which was officially standardized in December 2019. It includes a number of new features and improvements over previous versions of the language. Some of the most notable changes include:

  • Concepts: C++20 introduces a new feature called "concepts", which are a way to express constraints on template arguments. Concepts allow for more expressive type checking and improved error messages when using templates. Here's an example of how you might use a concept in C++20:
template<typename T>
concept Addable = requires(T a, T b) {
  { a + b } -> T;

template<Addable T>
T add(T a, T b) {
  return a + b;
Enter fullscreen mode Exit fullscreen mode

In this example, the Addable concept is defined to require that the type T can be added to another value of the same type (i.e., it has a + operator). The add function is then defined to take two arguments of type T, where T is constrained by the Addable concept.

  • Coroutines: C++20 introduces support for "coroutines", which are a way to write asynchronous code in a more synchronous style. Coroutines allow you to write code that can be paused and resumed, similar to how a generator works in Python. Here's an example of how you might use coroutines to asynchronously read from a file:
std::fstream file("example.txt");
std::string buffer;

co_await file.async_read_some(std::addressof(buffer), buffer.size());
Enter fullscreen mode Exit fullscreen mode
  • Modules: C++20 introduces "modules", which are a way to organize code in a more modular fashion. Modules allow you to group related declarations (e.g., functions, classes, variables) together and make them available to other parts of your code. They are similar to headers but faster to compile and more powerful.
export module my_module;

export int x = 1;

export void func() {
  std::cout << "Hello, World!" << std::endl;
Enter fullscreen mode Exit fullscreen mode
  • Ranges: C++20 introduces a new library for working with ranges of values, called the "ranges library". The ranges library provides a set of algorithms and views for working with ranges of values in a more functional style. Here's an example of how you might use the ranges library to filter and transform a range of integers:
std::vector<int> v {1,2,3,4,5};
auto rng = v | std::views::filter([] (int i) { return i % 2 == 0; })
            | std::views::transform([] (int i) { return i * 2; });
std::cout<<*rng.begin(); // Outputs 8
Enter fullscreen mode Exit fullscreen mode

This is just a small sampling of the new features in C++20, and there are many more improvements and changes in the language. C++20 provide more expressive and powerful tools for C++ Developers and make the language a more modern and powerful one.

Top comments (0)