Library Typedefs are fundamentally broken
Adam D. Ruppe via Digitalmars-d
digitalmars-d at puremagic.com
Tue Sep 23 10:48:20 PDT 2014
On Tuesday, 23 September 2014 at 17:36:33 UTC, Andrei
Alexandrescu wrote:
> (b) there are no significant ways to improve Typedef in ways
> that would be difficult to the struct-based approach (e.g.
> disallow implicit conversion to base type, adding constructors
> etc).
I think disallowing stuff is exactly why typedef (and Typedef)
are suboptimal - they are a package approach. And once you start
adding configuration options, you get a parameter list so long
you might as well just write the struct.
I do think there's value in some generic mixins for proxy member
forwarding though. Typedef is built on a Proxy mixin but it
brings everything. I'd say ideally, we'd break it up into various
pieces:
mixin Addition;
mixin Multiplication; /* these two might come together with mixin
Arithmetic; */
mixin Dereferencing;
mixin Indexing;
you know something like that. So now you can add operations
selectively... or add them all with alias this and selectively
disable them!
mixin template Addition(string proxy = "_") {
typeof(this) opBinary(string op : "+")(typeof(this) rhs) {
return typeof(this)(mixin(proxy ~ op ~ "rhs." ~
proxy));
}
}
struct Foo {
int _;
mixin Addition; /* Foo(10) + Foo(20) now yields Foo(30) */
}
struct NoAdd {
int _;
alias _ this; /* Foo(10) + Foo(20) yields int(30) */
mixin Addition; /* now we have all alias this but addition
gives Foo */
@disable mixin Multiplication; /* multiply is now statically
disallowed */
}
These mixins would take a wee bit more care than I showed here
and we'd want a battery of building blocks AND common
combinations, but I think this would blow even the ideal Typedef
utterly out of the water.
I think I posted this before, but you don't actually want
deferencing of an opaque HANDLE. typedef lets you do that since
it thinks it is a void*. alias this lets you do it, since it will
implicitly convert. But with the individual feature mixins, alias
this, and @disable, you can do whatever you want and have pretty
short, readable code.
More information about the Digitalmars-d
mailing list