Struct polymorphism?
Era Scarecrow
rtcvb32 at yahoo.com
Mon Oct 8 16:59:50 PDT 2012
On Monday, 8 October 2012 at 22:57:04 UTC, Ali Çehreli wrote:
> I don't know all of the design decisions behind opDispatch, but
> I would be happier to have to type "this." when inside the
> struct. Otherwise, any struct that defined opDispatch would
> miss out on compiler's static name checking.
>
> What if orig() has actually been a mistyped free-standing
> function name? Being forced to type this.orig() makes it
> explicit. And to me, this seems even better:
>
> return polyBase.orig(1);
Yes likely this is what will happen.. Just seems like it isn't
needed.
>> I can't just start adding 'this' to all my function as outside
>> normal functions/variables won't ever be seen.
>
> Sorry, I can't understand the problem that you describe in that
> sentence.
Hmmm added a this.writeln() and it worked fine without calling
opDispatch. How odd. Still seems like a compiler bug to me.
The idea behind that i'm experimenting with is in reality the
struct contained two functions. So..
struct S {
Something polyBase;
alias polyBase this; //opDispatch
string orig() {
return "some string";
}
string callsOrig() {
return orig();
}
}
With that everything is happy. Now if I rename orig to
Poly_orig, then callsOrig complains and the issue comes up. The
polyBase will check among the rules it has and adds Poly_ to the
functions while it's checking them (among other ones), before
finally calling S.Poly_orig() with all it's arguments.
So it will look something like this.
struct Data {
string msg;
}
struct Something {
Data data; //shared data
auto ref opDispatch(string op, Args ...)(auto ref Args args) {
static if (op == "orig") {
return (cast(S) data).Poly_orig();
} else {
static assert(0, op ~ " - Not found"); //205
}
}
}
struct S {
Something polyBase;
alias polyBase this; //opDispatch
//string orig() { //statically assigned
string Poly_orig() { //opDispatch calls now
return "some string";
}
string callsOrig() {
return orig(); //220
return this.orig();
return polyBase.orig();
}
string oddball() {
//asserts can't find blarg or Poly_blarg in opDispatch
return blarg(); //227
return this.blarg(); //228
}
}
test.d(220): Error: function expected before (), not
'this.polyBase.opDispatch!("orig")'
test.d(227): Error: function expected before (), not
'this.polyBase.opDispatch!("blarg")'
test.d(205): Error: static assert "blarg - Not found"
test.d(228): instantiated from here: opDispatch!("blarg",)
I'd rather have where once I get my code debugged for a struct
that I don't have to suddenly add this. or polyBase to all my
functions after I rename the functions to Poly_. If it's a
necessary evil than I'll accept it.
More information about the Digitalmars-d-learn
mailing list