alias to a property as an argument to a mixin template
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Sep 23 12:54:15 PDT 2012
monarch_dodra already answered, but since, I typed this, I may as well
post it :)
On Sun, Sep 23, 2012 at 8:49 PM, comco <void.unsigned at gmail.com> wrote:
> For this program I'm getting an "Error: need 'this' to access member x" at
> line (*). Does that mean that we cannot alias a property as an argument of a
> template mixin?
By using s.x, you're not referencing the property, but directly the
value s.x, which is known only at runtime: it cannot be a template
argument.
If x where a static member, you could probably use it, hence the error
message (need 'this', ...).
> So, using string mixins works, but explicit alias to the property name seems
> not to. Why is that?
a.stringof can be obtained for any symbol a, so s.x (or with(s) ... x)
just gives "s.x", which can be mixed in. It's transformed into a
string, transformation for which there is no need for 'this'.
> and is there any other way of achieving the result
> witout using template mixins
Sorry but... what result? Referencing a member inside a template?
Remember templates can be in another module, written years ago. If you
really want a template to act on a local value, either use a mixin
template, as you did, or reference the member by its name as a string:
import std.stdio;
mixin template T(string member)
{
void f()
{
mixin("writeln(" ~ member ~ ");");
}
}
struct S
{
int x;
}
void main() {
auto s = S(4);
mixin T!("s.x");
f();
} // prints 4
I see monarch proposed exactly the same way to do it...
More information about the Digitalmars-d-learn
mailing list