Determining whether a class has a method

Christopher Wright dhasenan at gmail.com
Thu Nov 29 17:32:55 PST 2007


Daniel Keep wrote:
> 
> 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

With the implication that, if I have a zero-arg constructor, I can just 
use that, and if I don't, then I can safely call ParameterTypeTuple on 
it. Thanks!


More information about the Digitalmars-d-learn mailing list