Testing if a function is defined in a module

Kirk McDonald kirklin.mcdonald at gmail.com
Wed Feb 21 11:47:15 PST 2007


mario pernici wrote:
> Carlos Smith Wrote:
> 
> 
>>"Kirk McDonald" <kirklin.mcdonald at gmail.com> wrote 
>>
>>: There are a few ways of phrasing this, but here's one:
>>: 
>>: static if (is(typeof(&YYUSERINIT))) {
>>:     // Do stuff with the function
>>: }
>>
>>Just tried with dmd 1.007, in a program
>>defining int a=0;
>>
>>  static if( is(typeof(main) == function ) )
>>    ...  
>>  static if( is(typeof(yymain) == function ) )
>>    ...
>>  static if( is(typeof(a) == int ) )
>>    ...
>>  static if( is(typeof(a) == float ) )
>>    ...
>>
>>All 4 tests gives what they suggest.
>>Ie: main is a function, yymain is not.
>>a is an int and not a float.
>>
>>Great !
>>
>>Looks like D wont miss the C preprocessor...
>>
> 
> 
> 
> Nice. I Tried to install dmd 1.007 for Linux, but the link is still for 1.006.
> 
> One can check the return type of the function with
>  static if(is(typeof(YYUSERINIT))) {
>     if( typeid(typeof(&YYUSERINIT)).toString() == "int()*")
>       writefln("YYUSERINIT is a int()*");
>   }
> 
> but it works independently of the arguments of the function, 
> int YYUSERINIT()
> or
> int YYUSERINIT(int a, int b)
> 
> 

Or one can use the IsExpression to derive the return type more sanely:

static if (is(typeof(&YYUSERINIT) Ret == return)) {
     writefln(typeid(Ret));
}

This is neatly wrapped by Phobos in the form of the 
std.traits.ReturnType template:

writefln(typeid(ReturnType!(YYUSERINIT)));

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list