C++23: “Hello World!” with Modern C++23

Whenever you learn a new programming language, the first program you write is often a “Hello World!” program that simply prints out “Hello World!” to the console. Up to now, for C++, this usually was something along the following lines:

#include <iostream>

int main()
    std::cout << "Hello World!" << std::endl;

This code snippets imports the required header, <iostream>, and uses std::cout to output text to the standard console.

With modern C++23, this simple program looks quite a bit different:

import std;

int main()
    std::println("Hello World!");

What has changed?

  • Instead of including the exact headers that are required, you simply import a single named module, std, provided by the standard.
  • Instead of using std::cout, stream insertion operators, and std::endl, you simply use std::println().

Unfortunately, at the time of this writing, there are no compilers yet supporting all the above new features, but soon there will be.

For the time being, if your compiler doesn’t support the named module std yet, you can simulate it yourself by writing your own named module called std. You can do this by writing a code file called std.cppm with the following contents:

export module std;

export import <iostream>;

You can extent this std.cppm named module with whatever header you need in your program.

Secondly, if your compiler does not support std::println() yet, you can simulate it with your own print module in a print.cppm file, e.g.:

export module print;

import <string_view>;
import <iostream>;
import <format>;

namespace std
    export template <typename... Args>
    void println(std::string_view sv, Args&&... args)
        std::cout << std::vformat(sv, std::make_format_args(args...)) << std::endl;

Warning: this is a very basic simulation of std::println(), which does not support all the features of the real std::println()!.


2 Comments so far »

  1. Stowy said,

    Wrote on November 8, 2023 @ 9:50 am

    Warning : putting code inside the `std` namespace is undefined behaviour and should be avoided. But it would be possible to keep the same code in a namespace named differently though

  2. Marc Gregoire said,

    Wrote on December 19, 2023 @ 6:55 pm

    Indeed, you are only allowed to put specializations of templates in the std namespace. Since this println() is a workaround for a missing std::println(), I did put it in std anyways. Good news, more and more compilers are supporting print() and println() out of the box.

Comment RSS · TrackBack URI

Leave a Comment

Name: (Required)

E-mail: (Required)