Capturing by reference with "visit" from std.variant

Smaehtin smaehtin at invalid.com
Tue Feb 20 16:01:11 UTC 2018


I'm trying to understand why the following doesn't work:

import std.stdio;
import std.variant;

void main()
{
     Algebraic!(string, int) test = "Test";

     test.tryVisit!(
         (ref string s) { s = "Why does this not work?"; }
     );

     writeln(test);
}

But this works fine:
*test.peek!string = "Works fine";

As far as I can tell, the "visit" template expands to something 
that ends up calling my handler like this:
if (auto ptr = variant.peek!T)
{
     handler(*ptr);
}

But seeing as the handler in my case takes a reference, shouldn't 
that work just fine? What am I missing?


More information about the Digitalmars-d-learn mailing list