D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 7356 - Implement KeyType, ValueType for hashes in std.traits
Summary: Implement KeyType, ValueType for hashes in std.traits
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2012-01-23 22:50 UTC by Andrej Mitrovic
Modified: 2012-04-19 18:57 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Andrej Mitrovic 2012-01-23 22:50:34 UTC
I've had a use-case for these but they were not in std.traits, so here's an implementation:

import std.traits;

template KeyType(AA)
   if (isAssociativeArray!AA)
{
   static if (is(AA V : V[K], K))
   {
       alias K KeyType;
   }
}

template ValueType(AA)
   if (isAssociativeArray!AA)
{
   static if (is(AA V : V[U], U))
   {
       alias V ValueType;
   }
}

If I get an OK I can make a pull for this (with documentation).
Comment 1 Kenji Hara 2012-01-24 06:05:29 UTC
I think the type-deduction template names should be 'KeyTypeOf' and 'ValueTypeOf'.

It is consistent with FunctionTypeOf and StringTypeOf (it's undocumented).
Comment 2 Andrej Mitrovic 2012-01-24 06:38:05 UTC
I've based it on ReturnType. There's a mix of these names, such as:
FunctionTypeOf
FieldTypeTuple

Some have "Of", others don't. I don't see what "Of" adds, except verbosity.
Comment 3 Jonathan M Davis 2012-01-24 08:05:06 UTC
I wouldn't expect the Of on them. It's awkward in comparison IMHO. I don't know why FunctionTypeOf and StringTypeOf have Of on them. But if Of is both used and not used (as appears to be the case), then I wouldn't use it - especially when the cases that _do_ use it are undocumented.
Comment 4 bearophile_hugs 2012-01-24 10:42:57 UTC
KeyType and ValueType are good enough names, I used the same in my code.
Comment 5 Kenji Hara 2012-01-26 04:07:44 UTC
(In reply to comment #2)
> Some have "Of", others don't. I don't see what "Of" adds, except verbosity.

IMHO, it comes from the typeof() feature.

First of all, and for fairness, `StringTypeOf` is the one that I added into Phobos in the past, so original XXXTypeOf is only FunctionTypeOf.

I'm not a native English speaker, but it seems to me that XXXTypeOf!(Y) is more natural than XXXType!(Y).
The former looks like a sentence, but latter like a noun. This kind of templates work like meta function, and function name usually contains verb. So I sometimes feel wrong about the latter.

And, 'KeyType' and 'ValueType' are often used in user code. I think we should avoid using generic name as the piece of library, as far as possible.