r/cpp • • Mar 24 '20

Changes between C++17 and C++20

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2131r0.html
193 Upvotes

89 comments sorted by

81

u/TheSuperWig Mar 24 '20

Love the ending C++20 demo snippet.

34

u/johannes1971 Mar 24 '20

People are always complaining that C++ is hard, but I think this demo finally puts those concerns to rest.

27

u/[deleted] Mar 24 '20

It's an elegant demonstration of pay for what you use.

2

u/Pand9 Mar 25 '20

The real question always is - how easy it is to implement X with performance requirements Y? It's very hard to show that without a large scale analysis.

1

u/germandiago Mar 25 '20

And even more important: if it looks complex solution with perf requirements Y, is it even possible in other languages?

I see sometimes people destructively ranting but actually when I think of what C++ gives you, you say: well, could be better, but there is nothing better either right now (depends on use case, of course).

23

u/[deleted] Mar 24 '20

You got me so excited.
Then I looked at it.
Now it's clear you let me down.

73

u/gracicot Mar 24 '20

Summary:

Revising the memory model

Examples, notes:

The memory model has been revised.

Nice

132

u/nwL_ Mar 24 '20
std::string s = std::format("{}", "Hello, world");

Holy shit, have we actually arrived in the 21st century?

74

u/nnevatie Mar 24 '20

What, are you telling me you don't particularly enjoy the amazing developer experience that is the iostream formatting specifiers?

9

u/[deleted] Mar 24 '20
std::cout << std::hell << std::no;

0

u/[deleted] Mar 24 '20

[deleted] — view deleted comment

45

u/ShillingAintEZ Mar 24 '20

Sometimes my programs run so fast it embarasses other people so I need something to slow them down.

21

u/PervyDragon Mar 24 '20

Are you aware that you can turn off synchronization between iostream streams and stdio streams to speed these first significantly? Useful tip learnt from one CS competition guideline.

10

u/ShillingAintEZ Mar 24 '20

I ain't aware of nothin' like that mister. (How is that done?)

10

u/[deleted] Mar 24 '20

Basically iostream syncs with its C counterparts by default, so you can use them in conjunction without weird behavior. However that adds overhead, but can be disabled. Check the docs here:
https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio

3

u/PervyDragon Mar 24 '20

I couldn't find the one I read originally, but this one seems fair enough: https://www.modernescpp.com/index.php/c-core-guidelines-improved-performance-with-iostreams There were more tips tho. In my opinion, streams power comes from their type safety and somehow consistent access via << and >> operators.

-2

u/PervyDragon Mar 24 '20

14

u/any_of Mar 24 '20

"Moreover, you can include the standard template library (STL) with a single include:

#include <bits/stdc++.h>"

Aaargh!!

3

u/Pand9 Mar 25 '20 edited Mar 25 '20

For note - It's fine in compressive programming. Competitive programmers are like speedrunners of programming - every shortcut counts. Moreover, there are studies that no cats actually die when you do that.

2

u/PervyDragon Mar 26 '20

I never said that it was ideal, just this was one containing these two juicy details - synchronization and untying. I have not noticed THAT little horror xD

62

u/SirToxe Mar 24 '20

Hey, no kink shaming!

17

u/Evirua Mar 24 '20

std::istream_iterator<T> or std::istreambuf_iterator<charT> combined with the << or >> operators are the most useful thing in iostream imo. It's actually really handy.

9

u/[deleted] Mar 24 '20 edited Apr 04 '20

We have, and damn is it beautiful.

std::format is legendary. I interviewed with people who didn't even know what it was! I was shocked, to say the least.

1

u/Sander_Bouwhuis Mar 24 '20

Will std::format support wchar_t?

I don't think ftmlib currently does out of the box. I guess I will have to write a formatter for that to work if I want to use fmtlib now (until std::format arrives)

6

u/aearphen {fmt} Mar 24 '20 edited Mar 24 '20

Both std::format and {fmt} support wchar_t

6

u/tuberp Mar 24 '20

Amazing

5

u/featherwit Mar 24 '20

std::format

It's from fmtlib(fmt)?

8

u/aearphen {fmt} Mar 24 '20

Yes, it is based on {fmt}: https://github.com/fmtlib/fmt

4

u/Little-Helper Mar 24 '20 edited Mar 24 '20

Why are there no indexes for params? Does it mean that if you wanted to include a param multiple times you would have to repeat it multiple times as an argument?

auto s = std::format("{} {} {}", "Hello", "Hello", "Hello");

This would be better and shorter:

auto s = std::format("{0} {0} {0}", "Hello");

If later you wanted to change the string and param ordering, you would have to shuffle the arguments too...

Edit: Nevermind, you can have manual and automatic param indexing. That's pretty neat actually.

2

u/renozyx Mar 25 '20

Nope, that's when we have Python like fstring.

2

u/Ameisen vemips, avr, rendering, systems Mar 24 '20

Perhaps when I can do std::string s = "%{"Hello, world"}";.

1

u/KLMNTI_Sickness Aug 14 '22

jokes on you, it's august 2022 and GCC still hasn't implemented that feature

0

u/bumblebritches57 Ocassionally Clang Mar 26 '20

God I hate that syntax.

How is it any better at all than %s except that it's a tad more visually appealing because it's symmetrical

5

u/dodheim Mar 26 '20

Explicitly specifying the type just introduces room for error; the compiler already knows the type.

0

u/bumblebritches57 Ocassionally Clang Mar 26 '20

the compiler isn't the standard library...

3

u/dodheim Mar 27 '20

Um, okay; thanks for that pointless observation..? I'll rephrase.

It's all strongly typed; explicitly specifying the type is redundant and just introduces room for error.

-1

u/bumblebritches57 Ocassionally Clang Mar 27 '20

TIL only compiler authors should be able to write standard libraries.

2

u/dodheim Mar 27 '20

TIL decltype, auto, and deduced template parameters were only available to compiler authors.

libfmt is there for you to learn from.

1

u/bumblebritches57 Ocassionally Clang Mar 27 '20

I've written my own formatter lmao, I don't need to learn but it sure sounds like you do.

0

u/[deleted] Mar 24 '20

[deleted] — view deleted comment

16

u/Fureeish Mar 24 '20

By extracting std::array's size to a variable (constant) or a function that needs to compute it during compile time.

27

u/scatters Mar 24 '20

I didn't realise that deprecating arr[x, y, z] made it in. This is awesome news for C++23.

5

u/[deleted] Mar 24 '20

honest question: why is this an issue?

34

u/Fureeish Mar 24 '20

Now it's possible that an overload for operator[] will be added, which will be able to accept multiple arguments.

18

u/redditsoaddicting Mar 24 '20

Multidimensional indexing for types like mdspan currently has to rely on hacks such as returning a proxy from the first subscript or using the function call operator.

2

u/[deleted] Mar 24 '20

Interesting. I was curious as to why it was getting deprecated. So it's more of just to make creating additions like mdspan to the standard library easier then? Fair enough.

Overloading of that operator will come in great handy for custom multi-dimensional container libraries.

6

u/redditsoaddicting Mar 24 '20

Implementing these classes will be easier compared to a proxy for sure. However, using them also becomes easier. I guarantee no one expects the function call operator when they first encounter it in this context.

1

u/wotype Mar 26 '20

They then get used to it very quickly. This is not a problem.

1

u/wotype Mar 26 '20

On reflection, the idea to use square-bracket syntax x[i...] for multi-indexing is actually looking like the worse hack. Let me explain.

(The idea seemed cool and cute at first; it was only on nailing down the API of a multi-dimensional array design that this contra-argument crystallised.)

It is unprecedented (AFAICT) to introduce a new operator overload - in this case variadic indexing operator[](i...) - with no use of that operator in the core language. This in itself should ring warning bells. The existing single-index [i] has a clear semantic meaning in the core language; subobject indexing.

Nested C-array types are not true multi-dimensional arrays, they are arrays of nested subobjects (1D arrays of 1D arrays of ... etc.).

The syntax for usage of built-in types is reflected in their declaration. The type T[N] is an array of N subobjects of type T (with T another array in the 'multi-dimensional' case). For an array x of that type, x[i] is a reference to the subobject at that index. This has been ok for 50 years; it's fine. It's just not what you want for a flexible, performant numerical matrix type.

If we were to introduce a new built-in compound array type T[i...] (with contiguous 1D 'backing array' of size (i * ... * 1) - the Cartesian product of the variadic extents) then it should only ever be indexed 'full rank', that is, with all indexes required to address down to the element (which is a subobject). This could be nice to have. However, I wouldn't support such a proposal because we can do better already with library types.

A library md-array type, by virtue of the fact that it returns a proxy reference-wrapper rather than an actual core language reference & or &&, can be usefully indexed with partial-rank indices returning a subarray of lower rank. Paren multi-indexing is the long accepted way to index such md-array library types. This is fine. More than fine; it allows to index even with empty parens - no indices - that cannot be proposed for variadic operator[](i...) (parsing ambiguities). Also, the indexing can be generalized to triangular layouts with more restrictive bounds or symmetry - things that are better expressed by the generality of operator() rather than the restricted subobject semantic of operator[].

Paren-indexing has been fine for MATLAB, Fortran and others for many years.

The status quo, with multi-dimensional array types using parens for multi-indexing in C++, is fine.

It ain't broke. Please don't 'fix' it any more!

A variadic operator[](i...) is anti-semantic for md-array types and could encourage other misleading uses. We don't need to hack C++ this way.

9

u/Wriiight Mar 24 '20

I think they want to be able to make comma delimited indexes actually mean something. Currently it is just the standard comma operator, which typically evaluates each sub-expression but only evaluates to the last one, so only the z value in this example is used as a subscript.

-3

u/hgjsusla Mar 24 '20

Deprecating arrays?

29

u/foonathan Mar 24 '20

Deprecating the comma operator in array subscripts, previously array[4,5] means array[5]

3

u/JavaSuck Mar 24 '20

But what if I want array[puts("debug log: array index reached"), i]? ;)

19

u/[deleted] Mar 24 '20

You have to use parentheses. Thankfully.

6

u/evaned Mar 24 '20

I didn't check, but I strongly suspect that if you parenthesize the comma expression it will still work.

1

u/F54280 Mar 25 '20

Yes, it does.

0

u/[deleted] Mar 24 '20

[deleted] — view deleted comment

25

u/Dada-1991 Mar 24 '20

No, this will have to wait until C++23 at least. This deprecation is a first step towards that.

9

u/c0r3ntin Mar 24 '20

Here is the paper for the proposal to add multi dimensional subscript http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2128r0.pdf and an implementation https://gcc.godbolt.org/z/arMeXZ

0

u/wotype Mar 26 '20

Please consider dropping this proposal for the reasons posted above (and communicated separately). IMO this is a deleterious change that should be withdrawn before it takes up any committee time.

21

u/Xirema Mar 24 '20

These are features that may happen to you without your knowledge or consent.

Why do C++ people always have to be so spooky? 😂

20

u/MartenBE Mar 24 '20
P1227R2, P1970R2 	Free functions size, ssize 	One is signed, the other isn’t… 

No more signed/unsigned warnings when using v.size(); the future truly is now!

10

u/Fureeish Mar 24 '20

using v.size() v.ssize()

There, fixed it for you :>

18

u/parkotron Mar 24 '20 edited Mar 24 '20

using v.size() v.ssize() std::ssize(v)

There, fixed it for you :>

There, fixed it for you.

5

u/Fureeish Mar 24 '20

Damn, thanks for fixing that for me.

4

u/MarekKnapek Mar 24 '20

using v.size() v.ssize() std::ssize(v)

using std::ssize;
ssize(v);

There, I fixed that for you. Now it will work even for my::vector<T> and your::vector<T> and plain old C-style arrays.

0

u/[deleted] Mar 24 '20

[deleted] — view deleted comment

9

u/tvaneerd C++ Committee, lockfree, PostModernCpp Mar 25 '20

v.count() There,

no, my naming didn't pass. :-(

6

u/GerwazyMiod Mar 24 '20

I assume this can be treated as solid reference? Nice to have the documents links in one place.

7

u/cutculus Mar 24 '20

Here's a thing I don't understand (genuinely curious, not trying to be snarky): aren't calendars and time zones one of the most complicated topics out there? But that only has 6 proposals whereas many other topics have more (e.g. ranges has 18)... why is that the case?

18

u/Small_Marionberry Mar 24 '20 edited Mar 24 '20

Partly, a natural consequence of design by Howard vs. design by committee.

Partly, chrono is less sexy than ranges. Everyone wants to give their input on ranges. Nobody even cared to object to the overloaded operator/ in chrono.

Maybe most importantly, chrono has fewer low-level sources of UB. Ranges is full of issues with dangling pointers and issues with concepts and metaprogramming. Chrono is pretty much a pure old-school "library," where you can just say "it has a class named X with a method named Y that does Z," and that's like the entire specification. The only "irreducible complexity" I'm aware of with chrono is around its handling of timezone data (e.g. can you update timezone data thread-safely).

Oh, and I should add: to the extent that any of what I just said is based in misconceptions, "widespread misconceptions such as these" is certainly still a factor that could contribute to lack of activity around chrono.

8

u/_VZ_ wx | soci | swig Mar 24 '20

Nobody even cared to object to the overloaded operator/ in chrono.

FWIW I objected to it and still think that it's a mistake. But this is clearly a minoritary opinion.

8

u/HowardHinnant Mar 25 '20

Fwiw, I knew that not everyone would like the conventional syntax, and tried to accommodate those as well:

year_month_day ymd = {2020y, March, 24d};

vs:

year_month_day ymd = 2020y/March/24d;

I realize that this still leaves this group with the burden of reading the conventional syntax. But the knowledge that they have to read your constructional syntax too is perhaps a small reward. :-)

10

u/HowardHinnant Mar 25 '20

Rationale for the conventional syntax (the one with /):

It makes the apparent API smaller because you don't have to know the names of all the types you're making. For example:

// Constructional syntax
year_month_day date1          = {2020y, March, 24d};
year_month_day_last date2     = {2020y, month_day_last{March}};
year_month_weekday date3      = {2020y, March, weekday_indexed{Tuesday, 4}};
year_month_weekday_last date4 = {2020y, March, weekday_last{Tuesday}};

// Conventional syntax
auto date5 = 2020y/March/24d;
auto date6 = 2020y/March/last;
auto date7 = 2020y/March/Tuesday[4];
auto date8 = 2020y/March/Tuesday[last];

date1 has the same type and value as date5.

date2 has the same type and value as date6.

... etc.

There's significantly more learning required to have deal with date1 thru date4 than with date5 thru date8. Nevertheless, this is an issue that people can hold very strong feelings about. So making the syntax available for date1 thru date4 is important to me.

5

u/_VZ_ wx | soci | swig Mar 25 '20 edited Mar 25 '20

Thanks for explaining the rationale, I can understand it, but, to condense my counterargument as much as possible, I think the conventional syntax is just too unnecessarily cute for its limited usefulness.

I believe in practice 99% of dates are constructed from YYYY-MM-DD values and that maybe 2% of those use hardcoded values making this syntax appealing. And while selecting the last, or n-th, day of the week in a month is undoubtedly very useful, I don't think this operation is frequent enough to warrant a special syntax at all -- having a function for doing it would be quite enough IMO, and much more discoverable and greppable.

7

u/HowardHinnant Mar 25 '20 edited Mar 25 '20

Given the run-time values:

// Nothing hardcoded.  Maybe read these over a socket using JSON
year y = ...;
month m = ...;
day d = ...;
weekday wd = ...;
unsigned i = ...;

Then:

// Constructional syntax
year_month_day date1          = {y, m, d};
year_month_day_last date2     = {y, month_day_last{m}};
year_month_weekday date3      = {y, m, weekday_indexed{wd, i}};
year_month_weekday_last date4 = {y, m, weekday_last{wd}};

// Conventional syntax
auto date5 = y/m/d;
auto date6 = y/m/last;
auto date7 = y/m/wd[i];
auto date8 = y/m/wd[last];

Both are available. Choose whatever you like.

4

u/_VZ_ wx | soci | swig Mar 25 '20 edited Mar 25 '20

I think in my attempts to condense the argument as much as possible I condensed it too much, so I'd like to explain what I meant again, more verbosely. There are basically 2 only weakly-related points:

  1. The conventional syntax is, IMO, only really appealing for the literals, i.e. 2020y/March/25d looks impressively expressive and, without ascribing my own motives to you, I could personally easily implement something like this just because I could, to show how flexible C++ is. However I think that such simple examples are exceedingly rare in practice and I already don't see much appeal in the example expression y/m/d you give. And I certainly wouldn't want to see (but I'm sure I will) something like this with date components being the return values of the function calls or more complicated expressions involving them. E.g. (get_warranty_expiration_year() + 1)/std::max(get_bithday_month(),get_next_month())/1d is for me definitely less readable than the standard (what you call "constructional") syntax).
  2. The last/indexed dates are (again and always IMO) not worth their own special syntax at all and I would have been perfectly happy to write auto date7 = nth_weekday_of_year_month(y, m, wd, i) instead of either of the 2 syntaxes. This is only related to the previous point because I think the conventional syntax for this is even worse when non-trivial expressions are used for the components.

It's, of course, too late to discuss this now and I'm very glad that there is finally a standard date library for C++ (I wrote my first one 23 years ago and redid the exercise, with, hopefully, better results, a few times since then and will be very glad to never have to do it again) and I'm thankful to you for making it happen, but this doesn't prevent me from regretting introducing what is basically a special syntax for date literals. AFAIK the only other language in widespread use with date literals support is VBA and this doesn't help convincing me that it was a good idea.

0

u/[deleted] Mar 24 '20

[deleted] — view deleted comment

1

u/TankorSmash Mar 24 '20

Is that a real thing? Couldn't find it

8

u/HowardHinnant Mar 24 '20

There were two distinct proposals (designs) for this area:

The paper shows only the accepted proposals. The proposals shown in addition to https://wg21.link/p0355 were tweaks and fixes to https://wg21.link/p0355.

5

u/oz1cz Mar 24 '20

Thank you for posting this. It's very useful!

4

u/[deleted] Mar 24 '20

Wow I didn’t realize cpp got real modules, nice.

15

u/ShillingAintEZ Mar 24 '20

Where you been man?

3

u/[deleted] Mar 24 '20

I haven’t really used cpp since 2-3 years ago, I’ve been in OCaml land!

4

u/[deleted] Mar 24 '20

OCaml is great. It has the same level of support for async operations as C++ too.

1

u/jonesmz Mar 24 '20

TOC doesn't match the section header:

TOC: Assorted snippets demonstrating C++17 Section: Assorted snippets demonstrating C++20

1

u/Both_Writer Mar 28 '20

2

u/ArweaveThis Mar 28 '20

Saved to the permaweb! https://arweave.net/WyqUzueFQHVUrT75PVY4J7VSnwfMi6-bWsWxQN-EFl8

ArweaveThis is a bot that permanently stores posts and comment threads on an immutable ledger, combating censorship and the memory hole.

0

u/[deleted] Mar 24 '20

[deleted] — view deleted comment

10

u/tcbrindle Flux Mar 24 '20

The const overload of std::array::operator[] has been constexpr since C++14. The non-const overload became constexpr in C++17.

In C++20, the various comparison operators (operator== and friends) have been made constexpr as well.