The most awesome "forward to member" solution?
Andrei Alexandrescu via Digitalmars-d
digitalmars-d at puremagic.com
Sat May 2 17:19:46 PDT 2015
Hey folks,
So in working with the allocator, a common matter has come again to the
fore: I need to forward certain functions to a member. Consider code in
https://github.com/andralex/phobos/blob/allocator/std/experimental/allocator/free_tree.d:
struct FreeTree(ParentAllocator)
{
...
static if (hasMember!(ParentAllocator, "expand"))
bool expand(ref void[] b, size_t delta)
{
return parent.expand(b, delta);
}
static if (hasMember!(ParentAllocator, "reallocate"))
bool reallocate(ref void[] b, size_t n)
{
return parent.reallocate(b, n);
}
static if (hasMember!(ParentAllocator, "allocateAll"))
void[] allocateAll()
{
return parent.allocateAll;
}
}
A simple solution have FreeTree support these functions would be to use
simple subtyping with alias this. However, I'd like more control than
that - yes, I want forwarding to work but not accessing the parent
object directly.
So I'm thinking of defining a mixin that would be used like this:
struct FreeTree(ParentAllocator)
{
...
mixin(forwardIfDefined("parent",
"expand", "reallocate", "allocateAll"));
}
and, boom, all appropriate forwarding is generated, either with sheer
definitions or by using opDispatch.
Furthermore, we should probably define this for Phobos because it's a
common thing people like to do.
Before embarking on this, does anyone have some code around that does
that kind of stuff?
Andrei
More information about the Digitalmars-d
mailing list