FAQ - Help and questions

How do C++ templates and concepts map to Rust generics and trait bounds?

#porting#cpp#genericspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A template becomes a generic function or type, and a concept or SFINAE constraint becomes a trait bound. Unlike a template, a Rust generic is checked when it is defined, not when it is used, so a missing bound is an error at the definition. Non-type template parameters become const generics.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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_ifT: PartialOrd
several requirementsT: PartialOrd + Copy, or a where clause
template <size_t N> struct Bufstruct Buf<const N: usize>
auto parameters and return typesimpl Trait in argument and return position
template specialisationnot 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.

src/main.rsrust
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());
}
text
Some(9) Some(1.5) None
a, b
16 64

If you leave the bound out, the error is at the definition of the function, before any caller exists:

rust
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]));
}
text
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#

  1. Port each template parameter to a type parameter, and ask what operations the body uses on it. Each operation is a trait bound: + is Add, < is PartialOrd, copying is Clone or Copy, printing is Display or Debug, a default value is Default.
  2. If the template was specialised for a few types, define a small trait with the operation and implement it for each type.
  3. Replace non-type parameters (array sizes, flags) with const generics.
  4. Prefer impl Trait for arguments and return values when you do not need to name the type.
  5. 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet