December 25, 2006
I have a need to define methods in a templated class that only conditionally exist.  For instance with a 'class Foo(T)', I'd like to give it an opNeg method as long as T is a type that can be negated.

So far so good, I can get that with:

class Foo(T)
{
    static if(is(typeof(-T.init))) {
    Foo neg() {
       auto ret = new Foo;
       ret.m_value = -m_value;
       return ret;
    }
    }

    T m_value;
}

1)
Is this something useful enough that it might be worth special syntax? Something like 'lazy' in front of the method declaration:

    lazy Foo neg() {
       auto ret = new Foo;
       ret.m_value = -m_value;
       return ret;
    }

The lazy meaning basically "leave this method out if it contains semantic errors".

2)
I can't figure out how to do the static if for opXXXAssign type methods.
static if(is(typeof(T.init+=T.init))) is always false, I guess because T.init isn't assignable.  Is there some way to do that check?


--bb
December 25, 2006
Bill Baxter wrote:
> I have a need to define methods in a templated class that only conditionally exist.  For instance with a 'class Foo(T)', I'd like to give it an opNeg method as long as T is a type that can be negated.
> 
> So far so good, I can get that with:
> 
> class Foo(T)
> {
>     static if(is(typeof(-T.init))) {
>     Foo neg() {
>        auto ret = new Foo;
>        ret.m_value = -m_value;
>        return ret;
>     }
>     }
> 
>     T m_value;
> }
> 
> 1)
> Is this something useful enough that it might be worth special syntax? Something like 'lazy' in front of the method declaration:
> 
>     lazy Foo neg() {
>        auto ret = new Foo;
>        ret.m_value = -m_value;
>        return ret;
>     }
> 
> The lazy meaning basically "leave this method out if it contains semantic errors".
> 
> 2)
> I can't figure out how to do the static if for opXXXAssign type methods.
> static if(is(typeof(T.init+=T.init))) is always false, I guess because T.init isn't assignable.  Is there some way to do that check?
> 
> 
> --bb

Pyd's automatic wrapping of operator overloads uses this trick. In that case, I know the type in question is always a struct or class, and so I check for the existence of the operator overload method directly:

static if (is(typeof(T.opAddAssign)))

This wouldn't work for the built-in types, but, on the other hand, the set of built-in types is finite, and you could fairly easily check for those some other way.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org