Checking if a function exists

Tyler Knott tywebmail at mailcity.com
Wed Feb 21 13:29:26 PST 2007


Michiel wrote:
> Tyler Knott wrote:
> 
>>> I'm not quite sure how to do this, but I'm sure one of you does. I need
>>> something like:
>>>
>>> static if ( functionExists(char[] .toString(T)) ) { ... }
>>>
>>> static if ( functionExists(char[] T.toString()) ) { ... }
>>>
>>> What is the real way to do this static check?
>>>
>>> Thanks!
>>>
>> Check out this
>> (http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.learn&article_id=6577)
>> thread in digitalmars.D.learn.  It answers your question exactly.
> 
> Well, not exactly. They only check for the function name, while I also
> need to check out the parameter.
> 
> And if I really want to do it right, also the return type. But I suppose
> a function named toString will probably return char[], so that's less
> important.
> 
>> For
>> non-static member functions of classes you'll need to test against a
>> reference to that class (although it doesn't need to be initialized). 
>> To get the return and parameter types you can use the templates in
>> std.traits (note: those templates (and DMD itself) will only reveal the
>> first overload of a function; there is no way to get the parameter list
>> for others).
> 
> That's too bad. Because std.string.toString is exactly the function I
> want to check for (among other, self-defined toString functions). And
> there are 20 such functions, all with a different parameter type.
> 
> I don't really need the whole list of parameters anyway. I only want to
> know if a function with a parameter type I specify exists or not.
> 
Hmm... I've only ever tried to get backwards (from knowing the function name to knowing all the overloads).  It seems 
that it's possible to find out if there's an overload for a specific parameter list:

import std.string;

class x{}
class y{}
extern char[] toString(x y);
void main()
{
	static if(is(typeof(toString(cast(x)null)))) pragma(msg, "This works.");

	//Note: you need to use the fully qualified name of toString if there's another toString in the local scope,
	//even if it uses a different overload which fits the type better.
	static if(is(typeof(std.string.toString(cast(uint)5)))) pragma(msg, "This too.");

	static if(is(typeof(toString(cast(y)null)))) pragma(msg, "Not this.");
}



More information about the Digitalmars-d mailing list