Hacker News new | ask | show | jobs
by volta83 1758 days ago
Rust traits are opt-in, C++ concepts are opt-out; you can think of C++ concepts as having a "blanket" implementation for all types, so you'd need to opt out using negative reasoning. For example, in C++, you can declare a trait:

    template <typename T>
    struct totally_ordered : std::false_type {};
and opt-in implement it for some types, but not for floats.

Then you can define a TotallyOrdered concept that requires the trait.

The C++ standard library didn't do this, so if you happen to accidentally implement a type with an API that conforms to TotallyOrdered, then it becomes "accidentally" TotallyOrdered, which is a big footgun.

1 comments

I think this might have been a better way to explain it than my attempt (since it looks like that confused some readers). However, you say C++ concepts are "opt-out", how does a Class opt out ?

If your Delicious concept mistakenly applies to my Desert, how do I as the author of the Desert tell C++ "No, no, when people ask if a Desert is Delicious tell them it isn't?".

Either the writer of the concept "opts-in to making the concept opt-in" (e.g. using the approach above), and that way, classes must opt in, _or_ classes opt-out by not implementing the concept API.

There is no way for a class to both implement the concept API and opt-out. The only way to support it is for the C++ concept writer to make their concept opt-in.