Compile-time Ducks
Andrej Mitrovic
andrej.mitrovich at gmail.com
Mon Feb 27 19:16:36 PST 2012
I couldn't believe my eyes when I tried out this code, but this thing
actually works:
import std.string;
import std.stdio;
// remove clashes
string safeName(T)() { return T.stringof.toLower() ~ "Res"; }
struct Result(T)
{
bool ok = true;
auto opCast(T = bool)() { return ok; }
mixin("T " ~ safeName!T() ~ ";");
mixin("alias " ~ safeName!T() ~ " this;");
}
Result!Node getNode()
{
typeof(return) node;
node.values["foo"] = "bar";
//node.ok = false; // try commenting it out!
return node;
}
struct Node
{
string[string] values;
}
void main()
{
Node node;
if (auto result = getNode())
{
node = result;
writeln("assigned");
}
else
{
writeln("no assignment!");
}
writeln(node);
}
No need for any tuple unpacking at all! 'auto return' actually calls
into opCast(bool), but it returns a node. How crazy is that?!
More information about the Digitalmars-d
mailing list