Checking that a template parameter is an enum
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Oct 1 15:37:57 PDT 2015
On 10/01/2015 03:26 PM, Nordlöw wrote:
> On Thursday, 1 October 2015 at 02:06:48 UTC, Fusxfaranto wrote:
>>> /** Returns: true iff all values $(D V) are the same. */
>>> template allSame(V...) // TODO restrict to values only
>>> {
>>> static if (V.length <= 1)
>>> enum bool allSame = true;
>>> else
>>> enum bool allSame = V[0] == V[1] && allSame!(V[1..$]);
>>> }
>>
>> std.traits to the rescue!
>>
>> http://dlang.org/phobos/std_traits.html#isExpressions
>>
>> Using isExpressions!V as a template constraint looks like the behavior
>> you're looking for.
>
> Thanks!
>
> BTW: Is there some way to turn the recursive definition of `allSame`
>
> template allSame(V...)
> if (isExpressions!(V))
> {
> static if (V.length <= 1)
> enum allSame = true;
> else
> enum allSame = V[0] == V[1] && allSame!(V[1..$]);
> }
>
> into an iterative definition?
Very quickly:
import std.traits;
template allSame(V...)
if (isExpressions!(V))
{
bool impl_(V...)() {
static if (V.length > 1) {
foreach (i, _; V[0 .. $ - 1]) {
if (V[i] != V[i + 1]) {
return false;
}
}
return true;
} else {
return true;
}
}
enum allSame = impl_!V();
}
unittest
{
static assert( allSame!());
static assert( allSame!(42));
static assert( allSame!(42, 42, 42));
static assert(!allSame!(42, 43, 42));
}
Ali
More information about the Digitalmars-d-learn
mailing list