C++ Logo

STD-PROPOSALS

Advanced search

Subject: [std-proposals] Request for opinion: Leaning on strong typing in STL.
From: Scott Michaud (scott_at_[hidden])
Date: 2020-07-22 12:50:52


Hello,

Do the library maintainers have any established opinion about strongly
typing parameters that can be ambiguous?

I'll illustrate what I mean with a concrete use case: std::vector.

In C++, there is a constructor that takes a single size_type and creates
a vector with n default-constructed elements. I need to frequently
bounce between languages, and other languages (such as Java and C#) have
their analogous constructor initialize the capacity without creating
initial elements. This makes it difficult to remember how any given
language's standard library behaves.

One solution (for C++) is to make an additional, explicit version of the
constructor that has intent-declaring parameters (which can be viewed in
the IDE's overload list). In this specific case, my initial thoughts
would be to create a std::reserve structure (and possibly a
std::default_initialize structure, etc.).

I made a usability demo of how this would work in Godbolt.

 1. Pretend that myVec doesn't exist and that the constructor belongs to
    std::vector
 2. The call to this->reserve() is just to make the usability demo work.
    If it was a part of std::vector then the implementation would be
    very different.
 3. The important part of the usability demo is the main() function.

https://godbolt.org/z/1zj4Mf

I briefly discussed this on the #Include C++ Discord channel, and
feedback was mostly positive. One person suggested converting the
constructor to a two-parameter version, which avoids creating the
structure. I think I like their idea better, especially since it frees
std::reserve from always being a size_t container, so I've included
their Godbolt revision below.

https://godbolt.org/z/4Kdncz

I am aware that these tag structures may cause issues with certain ABIs
if they're not inlined or otherwise optimized out. That said, I'm of the
opinion that they significantly improve code readability and clarity,
and that the compiler (as well as IDE code completion) can help prevent
errors. I expect that it would be especially good for people who are not
familiar with C++ because it removes a potential source of bugs and it
might simplify finding the function that they want.

Does this sort of design pattern align with the goals of the STL?
Any comments, concerns, or suggestions?
Any thoughts on where else this could be used?
Any thoughts on alternatives (and metrics where they win against this
pattern)?

Thanks for your time and your consideration!



STD-PROPOSALS list run by herb.sutter at gmail.com

Standard Proposals Archives on Google Groups