Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 41 additions & 14 deletions src/sumtype.d
Original file line number Diff line number Diff line change
Expand Up @@ -672,16 +672,9 @@ public:
* If the `SumType` is qualified, then its qualifiers are applied to
* [Types] before determining the index.
*/
size_t typeIndex(this This)()
size_t typeIndex() const
{
import std.traits: CopyTypeQualifiers;

alias Qualify(T) = CopyTypeQualifiers!(This, T);
alias QualifiedTypes = Map!(Qualify, Types);

return this.match!((ref value) =>
IndexOf!(typeof(value), QualifiedTypes)
);
return tag;
}
}

Expand Down Expand Up @@ -1320,8 +1313,17 @@ version (D_BetterC) {} else
@safe unittest {
alias MySum = SumType!(int, float);

assert(MySum(42).typeIndex == IndexOf!(int, MySum.Types));
assert(MySum(3.14).typeIndex == IndexOf!(float, MySum.Types));
static bool isIndexOf(Target, Types...)(size_t i)
{
switch (i) {
static foreach (tid, T; Types)
case tid: return is(T == Target);
default: return false;
}
}

assert(isIndexOf!(int, MySum.Types)(MySum(42).typeIndex));
assert(isIndexOf!(float, MySum.Types)(MySum(3.14).typeIndex));
}

// Type index for qualified SumTypes
Expand All @@ -1330,12 +1332,37 @@ version (D_BetterC) {} else
@safe unittest {
alias MySum = SumType!(const(int[]), int[]);

static bool isIndexOf(Target, Types...)(size_t i)
{
switch (i) {
static foreach (tid, T; Types)
case tid: return is(T == Target);
default: return false;
}
}

int[] ma = [1, 2, 3];
// Construct as mutable and convert to const to get mismatched type + tag
const x = MySum(ma);
auto x = MySum(ma);
const y = MySum(ma);
auto z = const(MySum)(ma);

assert(isIndexOf!(int[], MySum.Types)(x.typeIndex));
assert(isIndexOf!(const(int[]), Map!(ConstOf, MySum.Types))(y.typeIndex));
assert(isIndexOf!(const(int[]), Map!(ConstOf, MySum.Types))(z.typeIndex));
}

// Type index for differently-qualified versions of the same SumType
// Disabled in BetterC due to use of dynamic arrays
version (D_BetterC) {} else
@safe unittest {
alias MySum = SumType!(const(int[]), int[]);

int[] ma = [1, 2, 3];
auto x = MySum(ma);
const y = x;

assert(MySum(ma).typeIndex == IndexOf!(int[], MySum.Types));
assert(x.typeIndex == IndexOf!(const(int[]), Map!(ConstOf, MySum.Types)));
assert(x.typeIndex == y.typeIndex);
}

/// True if `T` is an instance of the `SumType` template, otherwise false.
Expand Down