Checking function callability in D1 (aka static try-catch)

Bill Baxter wbaxter at gmail.com
Sun Dec 7 04:21:27 PST 2008


On Sun, Dec 7, 2008 at 7:08 PM, Christian Kamm
<kamm-incasoftware at removethis.de> wrote:
>> This topic came up (again) fairly recently, and a solution was
>> proposed, but I found a case where that solution doesn't work.
>>
>> The objective is to do a static check to see if something is callable
>> with particular argument types, and if so call it.
>>
>> The proposed solution was to use '.init' like so:
>>
>>     static if (is(typeof( some_function(ArgType.init) ))) {
>>         // call some_function , or make an alias to it or whatever
>>     }
>>
>> But this doesn't always work if some function takes a ref argument.
>
> I didn't follow the original discussion, but what about:
>
> template makeValue(T...) { T makeValue; }
> template isCallable(alias s, ArgTy...) {
>  const bool isCallable = is(typeof(s(makeValue!(ArgTy))));
> }

That's pretty good.  Thanks.
Only problem is that it seems isCallable will generate an error.
Seems an is() is needed at the call site.

This seems to do the trick:

private template makeValue(T...) { T makeValue; }
private template Callable(alias s, ArgTy...) {
    static if (is(typeof(s(makeValue!(ArgTy))) FType)) {
        alias FType Callable;
    }
    else {
        static assert(false,
                      s.stringof ~ " not callable with args "~ArgTy.stringof);
    }
}
...
static if (is(Callable!(some_function, ArgType))) { ... }

--bb



More information about the Digitalmars-d mailing list