Alias template param - Undefined Identifier
Chris Williams
yoreanon-chrisw at yahoo.co.jp
Tue Mar 18 16:10:04 PDT 2014
On Tuesday, 18 March 2014 at 22:42:20 UTC, anonymous wrote:
> You can pass the variable name as a string:
> Or you can get the variable name from the alias parameter:
>
> import std.string: format;
> template gotoPath(alias path) {
> enum gotoPath = format(q{
> ...
> fs.chdir(%s);
> }, path.stringof);
> }
>
> I think I've read that .stringof shouldn't be used for code
> generation, but I can't think of anything better.
Your memory seems to be correct:
http://forum.dlang.org/thread/bug-11036-3@http.d.puremagic.com/issues/
It looks like the issue is that .stringOf is something generated
according to AST information and is thus intrinsically
compiler-specific. The ticket it links to suggest using
__traits(identifier, X) or 'one of the Phobos helper functions
such as "fullyQualifiedName".'
Annoying that formatting the string is required. I think you're
right that it's ignoring my alias parameter because I'm not using
it. Formatting doesn't accomplish anything except to use the
parameter. But in exchange, you have to relate your format
arguments to the %s entries, instead of the q{} contents just
being code.
import fs = std.file;
import std.stdio;
import std.string: format;
template gotoPath(alias path) {
enum gotoPath = format(q{
string currPath = fs.getcwd();
scope (exit) fs.chdir(currPath);
fs.chdir(%s);
}, __traits(identifier, path));
}
void doStuff(string targetDirectory) {
mixin(gotoPath!(targetDirectory));
writefln("b %s", fs.getcwd());
}
void main() {
writefln("a %s", fs.getcwd());
doStuff("/etc");
writefln("c %s", fs.getcwd());
}
More information about the Digitalmars-d-learn
mailing list