Nested Namespace and __has_include in C++17

I would like to give a simple tutorial on nested namespace and __has_include features in the C++17.

Nested namespace or a multi level namespace was hard in C++.

A time before C++17 the following had to be done.

namespace Framework
{
    namespace ToolLayer
    {
           namespace Applications
           {
                class ToolBaseClass
                {
                 };
           }
    }
}

This looks huge and difficult to understand.

In C++17 it can be used as follows:

namespace Framework::ToolLayer::Applications
{
    class ToolBaseClass
    {
    };
}

__has_include Source file inclusion

The syntax for this is as follows:

__has_include ( " filename " )
__has_include ( < filename > )

When the program consist of an include file with the “filename” then the statement evaluates to 1 or else it is 0. If filename which is a header file or a source file exist then it returns true.

An example shown in cppreference is here:

#if __has_include(<optional>)
#  include <optional>
#  define have_optional 1
#elif __has_include(<experimental/optional>)
#  include <experimental/optional>
#  define have_optional 1
#  define experimental_optional 1
#else
#  define have_optional 0
#endif
 
#include <iostream>
 
int main()
{
    if (have_optional)
        std::cout << "<optional> is present.\n";
 
    int x = 42;
#if have_optional == 1
    std::optional<int> i = x;
#else
    int* i = &x;
#endif
    std::cout << "i = " << *i << '\n';
}

On a C++ 17 compiler the following output is present

<optional> is present.
i = 42

Another simple example is as follows:

#if __has_include(<memory_resource>)
#  include <memory_resource>
#  define has_memory_resource 1
#else
#  define has_memory_resource 0
#endif

#include <iostream>

int main()
{
    if (has_memory_resource)
        std::cout << "Memory resource is present.\n";
    else
        std::cout << "Memory resource is not present on versions before C++17.\n";
    return 0;
}

memory_resource is a new header included in C++17. If the file memory_resource is present but we use C++14 compiler then it still displays that the file is present. But if the system never had installed the C++17 then it may not have this file and in that case, it will print the message saying that it is only available for versions from C++17.

Memory resource is not present on versions before C++17.

Previous: Template Argument Deduction

Next: Fold Expressions