xxxxxxxxxx
struct S
{
int value;
alias opApply = opApplyImpl!(int delegate(ref int) );
int opApplyImpl(DG : int delegate(ref int))(scope DG callback)
// int opApply(int delegate(ref int) callback)
{
if (auto result = callback(value)) return result;
return 0;
}
}
pure nothrow unittest
{
S xs = S(3);
int sum = 0;
foreach (x; xs) sum += x;
assert(sum == 3);
}
version(failure1)
pure nothrow unittest
{
S xs = S(3);
int sum = 0;
xs.opApply((ref int x) { sum += x; return 0; });
assert(sum == 3);
}
static bool b = false; // some global state to break pure
static foreach (i; 0 .. 4)
{
version(failure2)
pure nothrow unittest
{
static immutable exc = new immutable Exception("");
S xs = S(3);
int* p = &xs.value; // some pointer to break @safe-ty
foreach (x; xs)
{
static if (i == 0) { p = new int(x); } // allocates
static if (i == 1) { ++p; } // un-@safe
static if (i == 2) { b = true; } // impure
static if (i == 3) { throw exc; } // throws Exceptions
}
}
}