On Tuesday, 7 April 2015 at 17:21:09 UTC, Daniel Kozak wrote:
On Tue, 07 Apr 2015 16:40:29 +0000
via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com>
wrote:
Hi!
Excuse me if this is obvious, but I can't recall coming across
anything similar and a quick search returns nothing relevant:
struct Foo {
}
struct FooWrapper {
alias x_ this;
private Foo* x_; // doesn't work, as x_ is private
}
Basically, I want x_ to never be visible, except through the
"alias this" mechanism, at which point it should instead be
seen as public.
Assuming something like this is not already possible in a
clean way, I would like to suggest a tiny(I think) addition to
the language:
struct FooWrapper {
public alias x_ this; // overrides the visibility through
the alias;
private Foo* x_;
}
While I think this would be useful for the language, the
reason I want such a wrapper, is because I want to give
opIndex, toString, to a pointer, or, in fact just value
semantics, while keeping the rest of the interface through the
pointer.
I thought about using a class instead of a struct pointer, but
I am not sure about the memory layout for classes, nor about
the efficiency of overriding Object's methods, so I didn't
want to risk making it any less efficient. If someone could
shed some light about D's class memory layout and general
performance differences to a simple struct (or a C++ class for
that matter), that would also be great. In general, more
information about these sort of things would be great for us
also-C++ programmers. :)
Works for me:
struct M
{
void callMe() {
writeln("Ring...");
}
}
struct S
{
alias m this;
private M m;
}
void main(string[] args)
{
S s;
s.callMe();
}
Modules are like friends in C++: Even private members can be
accessed.
@ Márcio Martins:
You need a public getter function:
----
@property
@nogc
@safe
inout(Foo*) getFoo() inout pure nothrow {
return x_;
}
alias getFoo this;
----