www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Pattern to accept associative arrays

reply Steven Schveighoffer <schveiguy gmail.com> writes:
I've seen this pattern inside druntime to accept associative arrays for 
a template:

void foo(T : V[K], K, V)(T aa)

I was thinking about this, and realized, you can actually explicitly 
specify alternate K and V parameters, so that K and V may be different 
than the natural key and value type of AAs.

I've been trying to think of a way to "exploit" this by providing 
alternate K and V than what would be inferred, but I can't think of one. 
Mostly because AAs are such runtime-implemented types, that very few 
conversions between AA types are possible.

So for instance, K, and V are used exactly in byKeyValue to provide the 
types of the key and value (and not what is inferred from T).

A more "appropriate" signature would be something like this:

void foo(T)(T aa) if (is(T : V[K], K, V))

where one cannot specify K and V explicitly.

Can anyone think of a good reason why we should switch? The only one 
which I found works is converting a K to a const(K), but this doesn't 
allow any exploits from what I can tell. Aside from the reduction in 
symbol name size.

-Steve
Jul 05 2020
parent reply MoonlightSentinel <moonlightsentinel disroot.org> writes:
On Sunday, 5 July 2020 at 19:06:47 UTC, Steven Schveighoffer 
wrote:
 A more "appropriate" signature would be something like this:

 void foo(T)(T aa) if (is(T : V[K], K, V))
This doesn't work as expected because one cannot reference symbols introduced in a template constraint. You would need to redefine K and V inside of foo ...
Jul 05 2020
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 7/5/20 4:32 PM, MoonlightSentinel wrote:
 On Sunday, 5 July 2020 at 19:06:47 UTC, Steven Schveighoffer wrote:
 A more "appropriate" signature would be something like this:

 void foo(T)(T aa) if (is(T : V[K], K, V))
This doesn't work as expected because one cannot reference symbols introduced in a template constraint. You would need to redefine K and V inside of foo ...
Noted, but doesn't change the point that you shouldn't be able to explicitly set K and V separately from T. -Steve
Jul 06 2020