Partial class implementation

Bill Baxter dnewsgroup at billbaxter.com
Tue Jul 17 00:39:17 PDT 2007


Reiner Pope wrote:
> Bill Baxter wrote:
>> janderson wrote:
>>> Robert Fraser wrote:
>>
>>> There is no real point in arguing this.  My main argument is based on 
>>> code refactorbility and design.  I find free functions are much more 
>>> reuseable then member functions, look at algorithms in std (find, 
>>> sort ect...).
>>
>> Does that really hold true for D though?  Without Koenig lookup, free 
>> functions don't have the same flexibility they do in C++.  You can 
>> write generic template functions like find, sort, etc, where there is 
>> a single implementation and callers have to implement the concept it 
>> requires. But something like 'toString' as a non-member is pretty much 
>> impossible in D.
>>
>> --bb
> 
> I didn't realise there was an issue here, before; can you tell me if 
> this is what you are talking about?
> 
> ---
> 
> module a.b.c;
> 
> struct A {...}
> string toString(A) {...}
> 
> ---
> 
> module a.b;
> import a.b.c;
> 
> class B
> {
>     A getInstanceOfA() {...}
> }
> 
> ---
> 
> module b;
> import a.b;
> 
> void main()
> {
>     B b = new B();
>     auto a = b.getInstanceOfA();
>     string s = toString(a); // doesn't work
> }
> 
> ---
> 
> In this case, I can see it might be a surprise that it doesn't work, but 
> is there anything worse than that? What's wrong with just importing 
> a.b.c and carrying on? If you did any serious manipulations of 'a', then 
> you would have to declare the type 'A' *sometime*; so you'd end up 
> importing a.b.c anyway...
> 
> I'm just taking a guess at what you mean, though; if I'm completely off, 
> can you please explain?

I think that's ok, insofar as what you've written.  What you can't do is 
import more than one version of toString, even if they are unabmiguous 
w.r.t. the usual overloading rules:

----
module a;
struct A {  ... }
string toString(A) { ... }
----
module b;
struct B {  ... }
string toString(B) { ... }
----
import a;
import b;
void main()
{

}
----

That fails just importing the two modules, so I didn't bother actually 
trying to call the toString methods.

The above would work fine if you had the two flavors of 'toString' all 
consolidated in one module.  It would also work fine with 'static 
import' and explicit use of a.toString and b.toString.  But what doesn't 
work is resolving an overload to different modules based on the argument 
type.

Apparently it's a big hairy deal to implement and the bane of 
compiler-writers' existence.  But C++ allows it.  Walter believes it's 
not necessary, though.  And so far he seems right.  But it does mean you 
need to put some things inside classes (like toString) that could be 
free functions if protection levels were the only concern.

--bb



More information about the Digitalmars-d mailing list