How to avoid code duplication in static if branches?

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Mar 3 17:42:21 PST 2012


import std.stdio;
void check() { writeln("check"); }

struct Foo { bool isTrue = true; }
struct Bar { }

void test(T)(T t)
{
    static if (is(T == Foo))
    {
        if (t.isTrue)
            check();
    }
    else
    {
        check();
    }
}

void main()
{
    Foo foo;
    Bar bar;
    test(foo);
    test(bar);
}

I want to avoid writing "check()" twice. I only have to statically
check a field of a member if it's of a certain type (Foo).

One solution would be to use a boolean:
void test(T)(T t)
{
    bool isTrue = true;
    static if (is(T == Foo))
        isTrue = t.isTrue;

    if (isTrue)
        check();
}

But that kind of defeats the purpose of static if (avoiding runtime
overhead). Does anyone have a trick up their sleeve for these types of
situations? :)


More information about the Digitalmars-d-learn mailing list