define methods apart

Jonathan M Davis jmdavisProg at gmx.com
Sat Dec 18 12:45:13 PST 2010


On Saturday 18 December 2010 05:19:56 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.)

It is not supported. Functions are either free and unconnected to a type, or 
they're part of a type. You can't define one which is defined outside a type and 
yet considered part of that type. Declarations and definitions in general in D 
cannot be split. And splitting up definitions by defining a part of something 
elsewhere isn't supported at all - unless you count mixins, which just inject 
code from elsewhere, so while from the programmer's perspective the code is 
elswehere, from the compiler's perspective, it isn't really (since it's 
effectively copy-pasted in).

The closest you can get to having member functions outside of a type is to call 
functions on arrays as if they were member functions, as long as the first 
parameter is an array and is the same type of array. There is a good chance that 
this will become true for _all_ types at some point (the term used for this is 
uniform function call syntax), at which point, in a way, you'd be able to define 
functions for a type outside the type since then you could call any function 
which took the type as its first parameter as if it were a member function of 
that type. However, uniform function call syntax hasn't been implemented yet, so 
it only works for arrays.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list