View mode: basic / threaded / horizontal-split · Log in · Help
February 28, 2012
Compile-time Ducks
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?!
Top | Discussion index | About this forum | D home