Phobos 3 Discussion Notes - 02-01-2024

jmh530 john.michael.hall at gmail.com
Wed Feb 7 21:26:51 UTC 2024


On Wednesday, 7 February 2024 at 10:10:27 UTC, Atila Neves wrote:
> [snip]
>
> The problem with this approach, as C++ found out, is that 
> `Vector!(int, MyAlloc)` is a different type from `Vector!(int, 
> YourAlloc)`. The way I got around that is by defaulting to a 
> global allocator. This has its drawbacks as well of course, 
> because now everything is a virtual call.

If you need to allocate or deallocate, then it's useful to treat 
them as separate types. Otherwise it's not. Ideally the compiler 
(or maybe LTO?) would know when this leads to template bloat and 
fix it for you.

What about an `alias this` approach? For instance:

```d
struct BaseVector(T) {
     T* ptr;
     size_t length;
     // member functions that are common to all vectors
}

struct Vector(T, Alloc) {
     BaseVector!T baseVector;
     alias this = baseVector;
     // member functions to handle allocation and de-allocation
}
```

If you want to write functions that don't concern themselves with 
allocation, you can write them in terms of `BaseVector`. You 
avoid unnecessary template bloat because of implicit conversions. 
You can say that both `Vector!(int, MyAlloc)` and `Vector!(int, 
YourAlloc)` are both `BaseVector!int`s.

Is there a downside to this?


More information about the Digitalmars-d mailing list