Answer#
Both languages generate specialised machine code for each type a generic is used with. The difference is when the code is checked. A C++ template is checked when it is instantiated, so a missing requirement shows up as a long error at the use site (or as nothing, until someone uses a type that fails). A Rust generic is checked once, where it is written: the function may only use the operations that its trait bounds promise.
| C++ | Rust |
|---|---|
template <typename T> T f(T x) | fn f<T>(x: T) -> T |
requires std::totally_ordered<T> or std::enable_if | T: PartialOrd |
| several requirements | T: PartialOrd + Copy, or a where clause |
template <size_t N> struct Buf | struct Buf<const N: usize> |
auto parameters and return types | impl Trait in argument and return position |
| template specialisation | not available in stable Rust; use a trait with different implementations per type |
duck typing by use (x.size() works if it exists) | a trait that declares the method |
The program has a bounded function, a function with a where clause and a type with a const parameter. It was compiled and run with rustc 1.93.0.
use std::fmt::Display;
// C++: template <typename T> requires std::totally_ordered<T> T largest(const std::vector<T>&)
fn largest<T: PartialOrd + Copy>(items: &[T]) -> Option<T> {
let mut it = items.iter().copied();
let first = it.next()?;
Some(it.fold(first, |m, x| if x > m { x } else { m }))
}
fn show_all<T>(items: &[T]) -> String
where
T: Display,
{
items.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ")
}
// C++ non-type template parameter: template <size_t N> struct Buf { char data[N]; };
struct Buf<const N: usize> {
data: [u8; N],
}
impl<const N: usize> Buf<N> {
fn new() -> Self {
Buf { data: [0; N] }
}
fn capacity(&self) -> usize {
self.data.len()
}
}
fn main() {
println!("{:?} {:?} {:?}", largest(&[3, 9, 4]), largest(&[1.5, 0.5]), largest::<i32>(&[]));
println!("{}", show_all(&["a", "b"]));
println!("{} {}", Buf::<16>::new().capacity(), Buf::<64>::new().capacity());
}Some(9) Some(1.5) None
a, b
16 64If you leave the bound out, the error is at the definition of the function, before any caller exists:
fn largest<T>(items: &[T]) -> &T {
let mut m = &items[0];
for x in items {
if x > m {
m = x;
}
}
m
}
fn main() {
println!("{}", largest(&[1, 2, 3]));
}error[E0369]: binary operation `>` cannot be applied to type `&T`
--> src/main.rs:4:14
|
4 | if x > m {
| - ^ - &T
| |
| &T
|
help: consider restricting type parameter `T` with trait `PartialOrd`
|
1 | fn largest<T: std::cmp::PartialOrd>(items: &[T]) -> &T {
| ++++++++++++++++++++++The compiler even suggests the missing bound. The same mistake in a C++ template would only show up when someone instantiated it with a type that has no operator>.
How to do it#
- Port each template parameter to a type parameter, and ask what operations the body uses on it. Each operation is a trait bound:
+isAdd,<isPartialOrd, copying isCloneorCopy, printing isDisplayorDebug, a default value isDefault. - If the template was specialised for a few types, define a small trait with the operation and implement it for each type.
- Replace non-type parameters (array sizes, flags) with const generics.
- Prefer
impl Traitfor arguments and return values when you do not need to name the type. - If you use many types through one interface at run time rather than compile time, use a trait object (see the thread on virtual functions).
Common mistakes#
- Expecting template metaprogramming to translate. Rust has no general compile-time computation over types; many such tricks become a trait with associated types, or a
const fn. - Over-constraining a generic with bounds it does not use.
- Expecting specialisation. Two overlapping implementations of one trait are a compile error.
Related questions#
Do generics make Rust code slower or the executable bigger?#
Each type used gets its own compiled copy, as in C++, which can increase size. This thread did not measure it.
Where are C++ concepts?#
Traits play that role, and they also provide the implementations, not just the check.
Sources#
- The Rust Book, "Generic Types, Traits, and Lifetimes": https://doc.rust-lang.org/book/ch10-00-generics.html
- The Rust Reference, "Const generics": https://doc.rust-lang.org/reference/items/generics.html#const-generics