Hacker News new | ask | show | jobs
by steveklabnik 2839 days ago
There's two core differences.

The first is what happens when you get something wrong. Let's say you write a templated function. This is Rust syntax, mapping it to C++ is left as an exercise for the reader:

  fn foo<T>(x: T) {
      x.bar();
  }
Rust checks the types before expansion, not after. So you get this error:

  error[E0599]: no method named `bar` found for type `T` in the current scope
   --> src/lib.rs:2:9
    |
  2 |       x.bar();
    |         ^^^
In C++, this stuff is checked after expansion, so if you only pass things that have bar to foo, you're all good! It will compile. But when you pass something that doesn't, you'll get an error then.

This is a restriction, but one that leads to better error messages, and stronger checks. You'd need to write

  fn foo<T: Bar>(x: T)
where Bar is a trait that provides a bar method.

The second difference is what is allowed in generics: Rust only lets you use type parameters. We have accepted an RFC to allow constant expressions (the most straightforward of which is 'integers'), but it hasn't been implemented yet. C++ lets you do this today https://stackoverflow.com/questions/499106/what-does-templat... and https://en.cppreference.com/w/cpp/language/template_paramete... (they also have "template template parameters" aka higher kinded types https://en.cppreference.com/w/cpp/language/template_paramete...)

1 comments

It is worth adding that the C++ community has wanted to add something called "concepts" since a very long time. Rust traits sounds similar. So C++ will likely move in the direction of Rust here.
Yes. They're similar in ways, but also very different. I know that they have been added to the C++20 draft, but haven't gotten a chance to really dig in yet.