Why C++ is compile-time duck-typed (Templates vs. Traits)
template <typename T>
bool is_eq(T a, T b) {
return a == b;
}template <typename T>
T sum(T a, T b) {
return a + b;
}
Let’s start by just writing these down in our codebase.
- C++: template is not instantiated so it compiles.
- Rust: generic is verified for correctness by itself so we get an error:
error[E0369]: binary operation `==` cannot be applied to type `T`
--> foo.rs:2:14
|
2 | return a == b;
| - ^^ - T
| |
| T
|
help: consider restricting type parameter `T` with trait `PartialEq`
|
1 | fn is_eq<T: std::cmp::PartialEq>(a: T, b: T) -> bool {
| +++++++++++++++++++++
I cannot apply anything to the type T unless it is constrained to have that property.
Same with the addition case:
error[E0369]: cannot add `T` to `T`
--> foo.rs:6:14
|
6 | return a + b;
| - ^ - T
| |
| T
|
help: consider restricting type parameter `T` with trait `Add`
|
5 | fn sum<T: std::ops::Add<Output = T>>(a: T, b: T) -> T {
| +++++++++++++++++++++++++++
Since the body can be applied to all types that satisfy the constraints, I can determine if a substitution fails without looking at the body. Generics are instantiated purely by looking at their signatures.
In the case of traits, the property they provide is always just a collection containing types, values and functions.
Where in C++ I’d say:
- type
Ahas some functionfoo - type
Balso has some functionfoo - constrain
x.foo()to be valid via a concept
With Traits the sequence is:
- create a trait
Foo(whatever name) which embodies the property of havingfoo - instantiate the property for type
A - instantiate the property for type
B - constrain
x’s type to implementingFoo
trait Foo {
fn foo(&self) -> bool;
}
Now I can instantiate it for a type, this means that I imbue the type with having the property and provide its implementation:
impl Foo for u32 {
fn foo(&self) -> bool { false }
}
Instantiating a generic that requires Foo is valid only if the type itself is u32.
If I use it with something else I get an error:
error[E0599]: no method named `foo` found for type `f32` in the current scope
--> foo.rs:11:22
|
11 | return (2.0_f32).foo() && (2_u32).foo();
| ^^^
|
= help: items from traits can only be used if the trait is implemented and in scope
note: `Foo` defines an item `foo`, perhaps you need to implement it
--> foo.rs:1:3
|
1 | trait Foo {
| ^^^^^^^^^
A type that just has some function foo, does not satisfy the trait Foo.
In trait-based languages arithmetic operators are just trait instances, so to call my is_eq or sum functions, I must first implement PartialEq or Add respectively:
impl PartialEq for Person {
// the Rhs type defaults to Self
fn eq(&self, other: &Self) -> bool {
self.id < other.id
};
// ne (not equal) automatically provided
}
After this, Person{} == Person{} is valid.
If you need something like a template that instantiates other templates it is valid to implement instances generically as well:
impl<T> ToJSON for Vec<T>
where T: ToJSON
{
// depends on serialization of container type
}