Determining whether a class has a method

Daniel Keep daniel.keep.lists at gmail.com
Thu Nov 29 17:24:59 PST 2007



Christopher Wright wrote:
> Bill Baxter wrote:
>> I think you may be able to use an 'is' check + string mixin if the
>> name string is a compile time constant.
>> like
>>    static if(is( T.name == function ))
>>
>> then mixin-ify that like
>>
>> bool has_method(T, string name) {
>>    mixin("static if(is T."~name~" == function)) "
>>          "{ return true; } else {return false; }");
>> }
>>
>>
>> --bb
> 
> Very nice! It works for every situation but the one I need:
> 
> static if (is (T._ctor == function)) {
>    // This never happens.
> }
> 
> If there's no constructor defined for a class or any of its base
> classes, then ParameterTypeTuple!(T._ctor) fails, of course.
> 
> I guess I can work around this by requiring an explicit constructor, but
> I don't love it, especially since I can't provide a helpful error
> message in the failing case.

Can't you do something like:

static if( is( typeof(new T) == T ) ) ...

That should fail if T doesn't have a zero-arg constructor, at least AFAIK.

	-- Daniel


More information about the Digitalmars-d-learn mailing list