__has_include in C++17

No so long ago I discovered <optional> is a part of the C++17 standard. This header library is already shipped with GCC 7.0. Unfortunately, mingw-w64 (i.e. for Windows 🙂 ) currently supports GCC 6.3.

Lucky me, I found out that GCC 6.3 comes with the <experimental/optional> header and the std::experimental::optional wrapper. It makes some problems with naming because with the older version I have to add this “experimental” namespace and code is no longer portable.

After some tinkering I found __has_include directive coming with C++17 as well. You just pass header name you would like to include and it returns boolean, what makes it perfect for #if directives:

I had to make an ugly hack in here and put optional in the std namespace. The good thing is, the code works with both headers and fails to compile of neither is provided.

$ clang++ -std=c++1z main.cpp -o main.exe
$ ./main
no value

When <optional> support comes to MinGW-w64, I will have only a few includes to clean up. But the code will work even without it.