Trait objects with Box
already do heap allocation regardless, no?
Hm, you are right. With const generics and a bit of compiler magic we probably can remove additional heap allocation and double indirection. Cost of adding additional pointers to stack allocated TraitObject
struct is unfortunate, but it's probably will be the best solution. Although you'll pay this cost only if you use traits combinations (the more traits in your combination the fatter will be the pointer) so I think it fits under "zero-cost".
To be explicit, in this approach we'll change TraitObject
struct to:
pub struct TraitObject<const N: usize> {
pub data: *mut (),
pub vtables: [*mut (); N],
}
Which with N=1
will be equivalent to the current TraitObject
.