Thread overview
Question: What is the most elegant way to do this:
Aug 10, 2007
Frank Fischer
Aug 10, 2007
Daniel919
Aug 10, 2007
Frank Fischer
Aug 10, 2007
BCS
August 10, 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

August 10, 2007
Hi, I attached my solution.

Best regards,
Daniel


August 10, 2007
Daniel919 wrote:

> Hi, I attached my solution.

Nice one.

Is it possible *not* to use delegates? This is just because of efficiency, since it seems that the use of delegates always generates 'call'-statements in the assembly code (although this may not be a problem in my case).

But I really like your solution, it's better than mine, thanks.

Frank
August 10, 2007
Error decoding Quoted-Printable message: Unexpected 'i' when converting from type string to type ubyte