简体   繁体   中英

What is the portable way to forward-declare classes in an inline namespace in libc++?

The following code doesn't compile only when I specify -stdlib=libc++ to clang++ :

namespace std {
  class mutex;
}

void f(std::mutex &x);

#include <mutex>

void f(std::mutex &x) { }

note: candidate found by name lookup is 'std::__1::mutex'

I understand what is ::__1 there,

but to my eyes, libc++ breaks the API defined by the C++ standard:

It should be possible to forward-declare std::mutex because it should reside directly under std , shouldn't it?

Note that the compilation phase, rather than linking phase, is failing. So I don't think the answer to my question should be along the line of "because libc++ employs a different ABI from GNU libstdc++..."

but to my eyes, libc++ breaks the API defined by the C++ standard:

Actually, it does not. The standard specifies in [contents]:

It is unspecified whether names declared in a specific namespace are declared directly in that namespace or in an inline namespace inside that namespace.

libc++ is allowed to put mutex in inline namespace __1 . Note that there are good reasons for wanting inline namespaces, and typically as the user you don't even care if they exist or not.

To your specific question, you can still forward-declare std::mutex with libc++... you just have to include all the namespaces (see this question for how to detect -std=libc++):

namespace std {
#ifdef _LIBCPP_VERSION
    inline namespace __1 {
        struct mutex;
    }
#else
    struct mutex;
#endif
}

However, from [namespace.std]:

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.

A forward-declaration is still a declaration, so even the above version which accounts for inline namespaces is undefined behavior. So prefer to do it the direct way:

#include <mutex>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM