Question: What is the most elegant way to do this:

Frank Fischer frank.fischer at s2001.tu-chemnitz.de
Fri Aug 10 06:18:59 PDT 2007


Hi,

I want to write a template-function in the following way:

--
void func(T)(T x) {
    static if (is(T : TypeA)) {
        /* do CODE1 with x */
    }
    else {
        TypeA _x = cast(TypeA)x;
        if (x !is null) {
            /* do CODE1 with _x */
        }
        else {
            /* do CODE2 with x */
        }
    }
}
--

The function 'func' should check if T is of type TypeA (or a subclass). If
this is the case, CODE1 should be applied to x. If this is not the case,
the function tries to dynamic-cast x to TypeA. If successful, apply CODE1
to _x, otherwise do something different.

It is important for me, that no dynamic-cast is tried if T is of type TypeA.
Furthermore I'd like to have a general (meta-programming?) tool to do this
pattern in various functions.

As an extension, it would be cool if the test can be done on an arbitrary
number of arguments of the function. Furthermore it should be possible, to
do this check againt more than one type, i.e. first do the static test
against TypeA then TypeB and so on and if all those tests fail, do the
dynamic-cast-test. If x is of TypeA (static or dynamic) apply CODE1, if
it's of TypeB apply CODE2, ...

What would be the cleverest way to do this? Of course, CODE1 (for example)
should be there only once and it would be nice if it's not necessary to
write more than one function (i.e. everything necessary, beside the
meta-programming-stuff, should be written in the body of 'func').

Thanks,
Frank



More information about the Digitalmars-d-learn mailing list