Bug 9849 – Introduce BaseElementType and BaseRangeType

Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-03-31T14:45:00Z
Last change time
2016-08-27T23:18:34Z
Assigned to
nobody
Creator
andrej.mitrovich

Comments

Comment #0 by andrej.mitrovich — 2013-03-31T14:45:32Z
Implementation: template BaseElementType(Type) { static if(is(Type T : T[N], size_t N)) { alias BaseElementType = BaseElementType!T; } else static if(is(Type T : T[])) { alias BaseElementType = BaseElementType!T; } else static if(is(Type T : T*)) { alias BaseElementType = BaseElementType!T; } else { alias BaseElementType = Type; } } /// unittest { static assert(is(BaseElementType!int == int)); static assert(is(BaseElementType!(int[]) == int)); static assert(is(BaseElementType!(int[][]) == int)); static assert(is(BaseElementType!(int[1][2]) == int)); static assert(is(BaseElementType!(int**) == int)); } Note how this is different from ElementType in std.range. Here we're looking for the furthest element type, and we do it through type introspection rather than trying to invoke a .front property. The above is used for types, however this can also be implemented for ranges, where we would look recursively into a range until its front property does not return a range. An implementation: template BaseRangeType(R) if (isInputRange!R) { static if (is(typeof((inout int = 0){ R r = void; return r.front; }()) T)) { static if (isInputRange!T) alias BaseRangeType = .BaseRangeType!T; else alias BaseRangeType = T; } else static assert(0); } struct Range1 { int front(); void popFront(); bool empty; } struct Range2 { Range1 front(); void popFront(); bool empty; } static assert(is(BaseRangeType!Range1 == int)); static assert(is(BaseRangeType!Range2 == int));
Comment #1 by andrej.mitrovich — 2013-03-31T14:46:38Z
Apologies for forgetting to include imports, add these: import std.array; import std.traits; import std.range;
Comment #2 by andrej.mitrovich — 2016-08-27T23:18:34Z
The enhancement request lists no actual use-cases. If anything it would just be another extra function in Phobos with very little actual use or benefits.