From the D Blog: (Ab)using Overload Sets to Create Ad-Hoc Template APIs

jmh530 john.michael.hall at gmail.com
Wed Jul 22 13:14:50 UTC 2026


On Wednesday, 22 July 2026 at 07:21:51 UTC, Kapendev wrote:
> On Wednesday, 22 July 2026 at 01:01:31 UTC, jmh530 wrote:
>> On Tuesday, 21 July 2026 at 23:53:48 UTC, Kapendev wrote:
>>> On Tuesday, 21 July 2026 at 23:41:28 UTC, jmh530 wrote:
>>>> In the part about GVec, what if you already have code that 
>>>> relies on the library with GVec2/3/4 and want to integrate 
>>>> it with this?
>>>
>>> I think it's an easy change. Something like:
>>>
>>> ```d
>>> // Old: GVec2(T) { ... }
>>> GVec(T, int N : 2) { ... }
>>> alias GVec2(T) = GVec!(T, 2);
>>> ```
>>>
>>> The reason why I haven't done it is because I prefer the 
>>> simplicity of a single template argument. It's an opinion. I 
>>> might change it one day.
>>
>> I'm thinking about the situation where you have functions that 
>> take on an old GVec2 as an input and you don't have the 
>> ability to change the original GVec2 source code. Wouldn't you 
>> have two GVec2's in scope if you do something like this?
>
> Kinda hard to think of a case like that.
> If you have two of those in the same scope then that would be a 
> bit annoying. Avoiding the alias `GVec2` and using the new 
> version directly would help. So you use `GVec2` for the old one 
> and `GVec!(float, 2)` for the new one.

See my reply to monkeyyy [1], if you have the aliases, it doesn't 
compile.

What you actually have to do is remove the aliases and do 
something like this

```
--- test.d
import std.stdio: writeln;

import gvec;

struct GVec(int N : 2, T) { GVec2!T _data; alias _data this; }
struct GVec(int N : 3, T) { GVec3!T _data; alias _data this; }
struct GVec(int N : 4, T) { GVec4!T _data; alias _data this; }

void main()
{
     GVec2!int x = GVec2!int(1, 2);
     foo(x);
}
--- gvec.d
import std.stdio: writeln;

struct GVec2(T) { T x, y; }
struct GVec3(T) { T x, y, z; }
struct GVec4(T) { T x, y, z, w; }

void foo(GVec2!int x) {
     writeln(x.x);
     writeln(x.y);
}
```

[1] 
https://forum.dlang.org/post/mtwxxyfdpghwhroohrzi@forum.dlang.org


More information about the Digitalmars-d-announce mailing list