Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no <stlfwd> header and can the non-existence of it be considered a defect?

The standard library includes an <iosfwd> header, that (forward) declares all streams including any typedefs 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 / typedefs 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 namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std.

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 typedefing 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.

like image 697
Xeo Avatar asked Jun 11 '11 02:06

Xeo


1 Answers

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.

like image 56
Mark B Avatar answered Nov 03 '22 21:11

Mark B