Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> 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.


Indeed. 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.


They are also great for poor man's reflection, you can combine concepts with C++ traits (not the same as Rust's) and constexpr if, to check if the given type supports some specific capabilities.


In Qt Creator I can see the interface defined by a concept upon autocomplete


Rust 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: