The standard library includes an <iosfwd>
header, that (forward) declares all streams including any typedef
s and defines the char_traits
template, including the specializations.
Sadly, there is no such <stlfwd>
header that (forward) declares all the common STL datatypes and functions like vector
, map
, less
, sort
, etc. Even more sadly, user code is not allowed to add such declarations / typedef
s to the std
namespace, as per
§17.4.3.1 [lib.reserved.names] p1
:
It is undefined for a C + + program to add declarations or definitions to namespace
std
or namespaces within namespacestd
unless otherwise specified. A program may add template specializations for any standard library template to namespacestd
.
Yep, that covers the case of (forward) declarations, even if the types already exist in the standard library. Of course, most (all?) compilers will behave perfectly normal even if one adds such declarations, but strictly and language lawyer speaking, it is undefined behaviour. I find this especially tedious for typedef
ing standard containers, like:
// how to forward declare map and string?
typedef std::map<std::string, std::string> Attributes;
Now, can this be considered a defect?
I mean both the non-existence of a <stlfwd>
header (or better, <stdfwd>
, covering <iosfwd>
too) and the ban on declarations already existing in the standard library.
Also, according to this question, if one (forward) declares the standard container, algorithms and functors / functionals exactly as demanded by the standard, the code should be perfectly valid (if it weren't for the ban of user-made declarations in the std
namespace), because implementations aren't allowed to add any hidden/defaulted template parameters.
I am asking this because I'm thinking of eventually submitting a defect report regarding this.
What would be the purpose of forward declaring say less
or sort
or really any other algorithm? If you're passing a general purpose algorithm around it will almost certainly be as a template type and not need a forward declaration at all.
That leaves us with the container types. There are definitely cases where forward declarations of them would be useful but I suspect that it was simply decided that as each container definition is relatively simple (compared to iostreams) it would be preferable to just use the full include rather than a <containerfwd> include for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With