define methods apart

Christopher Nicholson-Sauls ibisbasenji at gmail.com
Sun Dec 19 01:37:37 PST 2010


On 12/18/10 07:19, spir wrote:
> Hello,
> 
> 
> I cannot find a way to define methods (I mean "member functions) outside the main type-definition body:
> 
> struct X {}
> void X.say () {writeln("I say!");}
> ==>
> Element.d(85): semicolon expected, not '.'
> 
> Do I overlook anything, or is this simply impossible? In the latter case, what is the problem?
> (In many languages, not only dynamic ones, method are or at least can be defined apart.)
> 
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com
> 

As bearophile says, it just isn't the "D way" to do things.

But, if you absolutely must (or just want to, for "playing" sakes) there
are ways of faking it using opDispatch.  Here's one I just tossed
together and tested (DMD 2.050) right now.

--------------------------------------------------
import std.stdio;

class Foo {

	static addExternalMethod( void function( Foo ) fp, string id ) {
		_methodRegistry[ id ] = fp;
	}
	
	private static void function( Foo )[ string ] _methodRegistry;
	
	this ( string name ) {
		_name = name;
	}
	
	@property const
	string name () { return _name; }
	
	private string _name;
	
	void opDispatch ( string Id ) () {
		if ( auto fp = Id in _methodRegistry ) {
			(*fp)( this );
		}
	}
	
}

void _foo_sayHello (Foo self) {
	writefln( "Hello, I am %s.", self.name );
}

static this () {
	Foo.addExternalMethod( &_foo_sayHello, "sayHello" );
}

void main () {
	auto foo = new Foo( "Grant" );
	foo.sayHello();
}
--------------------------------------------------

Of course, there is the obvious issue of the 'method' signatures having
to be the same, in this case.  You'd have to find a better solution to
the 'registry' issue, at the very least, in order to make it really usable.

Generally speaking, though, I'm not sure what the real value would be in
doing this in D.  Did you have a particular use case in mind, or was it
just idle exploration?

-- Chris N-S


More information about the Digitalmars-d-learn mailing list