dynamic classes and duck typing

Lutger lutger.blijdestijn at gmail.com
Sun Nov 29 05:02:24 PST 2009


biozic wrote:

> Le 29/11/09 13:16, Michel Fortin a écrit :
>> On 2009-11-29 06:14:21 -0500, "Simen kjaeraas" <simen.kjaras at gmail.com>
>> said:
>>
>>> That is because your opDispatch is instantiated no matter what the name
>>> is, but only does something sensible if it's foo. Try this:
>>>
>>> string opDispatch( string name )( ) {
>>> static if ( name == "foo" ) {
>>> return "foo";
>>> } else {
>>> static assert( false, "Invalid member name." );
>>> }
>>> }
>>
>> Wouldn't this be even better?
>>
>> string opDispatch(string name)() if (name == "foo") {
>> return "foo";
>> }
>>
>> I haven't tested that it works though.
>>
> 
> It doesn't improve the error message, but it works. It's been a long
> time since I used D: I didn't know this syntax!

Don has made a patch to improve these kind of error messages in templates, 
but that will probably come after D2 is finalized (doesn't affect the 
language).

If you want to resolve the symbol at runtime I think you can get a better 
error message for throwing an exception or assertion. I don't have the svn 
dmd, so this isn't tested:  

void opDispatch(string name)(string file = __FILE__, int line = __LINE__) 
{
  if ( !dynamicDispatch(name) )
  {
    // line and file are default initialized from the call site:
    throw new MethodMissingException(name, file, line);
  }
}








More information about the Digitalmars-d mailing list