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, andstd::endl
, you simply usestd::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()
!.