C++ Logo

sg20

Advanced search

Re: [SG20] Difficulties in teaching the use of C++20 concepts

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Sun, 15 Dec 2019 17:50:49 +0200
On Sun, 15 Dec 2019 at 15:56, Martin Beeger via SG20
<sg20_at_[hidden]> wrote:
> But to sum up regarding the use of auto, a post-C++20 guideline could be (a hopefully much more well-formulated and littered with examples version of the following):
>
> 1. whenever the type of the expression is mentioned on the right hand of a statement, just put auto on the left side for brevity instead of repeating yourself on the left hand.
>
> 2. whenever auto represents a generic value whose type is not known locally, look for a fitting named constrained and apply it for the auto parameter to ensure semantic correctness of the using code without loss of genericity.
>
> 3. whenever you develop code and you are not thinking of its correctness in terms of concrete types but in form of general concepts, use auto.
>
> 4. whenever you write functions, try to think of the problem in you solve as a abstract problem and about generic solutions, not only about one for your concrete types. Look for an exisisting solution to a general problem.
>
> As you apply the last rule to your coding (in line with Sean Parents Better Code principles) you will either find an a solution already there, if you don't, what you will write will now fall under rule 3, which will in turn then fall under rule 2.
>
> Is that an accurate representation of what the your AAA (now AA) rule intends to achieve and how you would advise in a C++20 world?
>
> I as and AAA skeptic can totally get behind this new version.

While I remain an AA/AAA skeptic, the constrained version of it
certainly gives an intriguing almost-best-of-all-worlds
facility that is nicely in-between: it allows enforcing concrete types
if the programmer so chooses (which happens
in various cases on API boundaries, it's a "tell me at first chance if
I didn't get what I expected"), which imho isn't
"brittle", it's perhaps "rigid", and as a stretch "robust", in
contrast with the unfortunate connotations of "brittle".

See https://wandbox.org/permlink/6G5Afjy2m6EO2TMz

tl;dr for those who wish to see it inline:

#include <concepts>

int f() {return 42;}

long g() {return 555L;}

int main()
{
    std::same_as<int> auto x = f();
    std::same_as<long> auto y = g();
}

No conversions. No blind duck typing either. If I change the return
type of f() to be something else than int,
I get a compiler error exactly where I want it, no later, and
certainly not at run-time when I try to figure out what
on earth got instantiated with a type that wasn't what I thought it was.

Received on 2019-12-15 09:53:26