4 ms·
> So what are concept good for? I think it is mostly about documenting your code. Emphasis mine. While it is somewhat good as documentation, sometimes static_a
by planede 3y ago
> So what are concept good for? I think it is mostly about documenting your code.
Emphasis mine. While it is somewhat good as documentation, sometimes static_assert with a custom diagnostic message is sometimes better for this purpose.
The hidden power of concepts/constraints is the way it shapes overload sets. You can have something like:
template <forward_range R>
void foo(R&& r) {
/* some generic algorithm */
}
template <random_access_range R>
void foo(R&& r) {
/* optimized for random access */
}
and it will work if you pass a random access range, as the compiler can deduce that it's more specific than a forward range to resolve the ambiguity. Prior to concepts writing code that did this was way more cumbersome.
- gpderetta 3y agoIndeed. I haven't found concepts to be very good at generating error messages. But they are great for documentation and to get rid of SFINAE hacks for overloading. The shorter template syntax is a bonus. edit: concepts should also allow for better IDE tooling, for example proper completion inside template functions; although it is supposed to work, I didn't notice it firing yet in clangd.
- pornel 3y agoRust requires trait bounds (its equivalent of concepts) to type-check the template code at definition site, when it's written, not at the instantiation site where it's used. This results in much better error messages. The downside is that trait bounds for numeric code are awfully verbose, and you can't sneak in a printf without declaring it as a requirement.