Reputation: 30068
The C++ standard does not allow code to forward declare classes in namespace std
, even when they are not templates.
I see no good reason to do this, so I wonder what is the motivation?
It could be a huge compile time improvement. For example std::mutex
is a simple class, but the <mutex>
header drags in a ton of stuff (at least on my implementation).
If somebody wonders why I am making a distinction between templates and non-templates, then it is because template instantiations can differ significantly based on what template arguments are provided, so I guess that might be trickier to implement/support.
Upvotes: 4
Views: 315
Reputation: 170153
for example
std::mutex
is a simple class
How do you know? The standard describes it as a class, but nothing is stopping an implementer from doing
namespace std {
using mutex = _Internal_detail::_PthreadMutex;
}
Granted, I omitted some (likely very verbose and expert friendly) checks for when this alias should be set. But this is a valid implementation technique!
Now if you add your forward declaration, you will get an error since an alias and a class are different things. That makes such forward declarations inherently non-portable, and as such, they are deemed to produce undefined behavior.
Upvotes: 6