3 ms·
I would say that Rust generics are less complicated (and less powerful) than C++ templates. C++ has stuff like SFINAE which gets regularly used to do all kinds
by Manishearth 10y ago
I would say that Rust generics are less complicated (and less powerful) than C++ templates. C++ has stuff like SFINAE which gets regularly used to do all kinds of black magic. C++ templates also are monomorphization-time typechecked -- this makes them a more powerful form of macro, and this does mean that C++ templates let you do a lot more than Rust generics.
Rust generics are early-typechecked. You can't call a method on a generic parameter unless you have bounds saying that you can. And, similarly, you can't substitute type parameters in places where the bounds don't agree. This means that there are much clearer API boundaries (no more documentation snippets saying "T must have a method .foo()" or "specialization FooTrait<T> must exist") and cleaner error messages, but less metaprogramming power. Rust is hoping to make up for that loss of metaprogramming power elsewhere, but in a vacuum C++ templates are more powerful (though they have other downsides)
(FWIW you can index BTreeMap or hashmap as well with []; the difference is that [] will panic if it can't find the item. entry() gives a reference to the entry which you can check for emptyness and update before pushing if necessary. In C++ most things get implicitly initialized so that's not a problem)
- bjourne 10y agoI stand corrected. Though I've rarely seen templates used for anything other than for implementing generic types. Certainly not in the C++ code bases I've worked on. For example, I know templates specializing on values are possible but I haven't seen any non-toy examples making use of that.
- Manishearth 10y agoYou've been luckier than I, then :) I've not seen much use of SFINAE, just enough SFINAE is a "core" type that makes it infect everything.