variant visit not pure?

Steven Schveighoffer schveiguy at gmail.com
Thu May 7 14:53:10 UTC 2020


On 5/7/20 5:22 AM, learner wrote:
> Good morning,
> 
> Is there a reason why std.variant.visit is not inferring pure?
> 
> ```
> void test() pure {
>      Algebraic!(int, string) alg;
>      visit!( (string) => 0, (int) => 0)(alg);
> }
> 
> Error: pure function test cannot call impure function 
> test.visit!(VariantN!(16LU, int, string)).visit
> ```
> 
> Thank you

Because VariantN (the base of Algebraic) can literally hold anything, it 
cannot be pure, @safe, nothrow, @nogc.

As others have recommended, I suggest using TaggedAlgebraic. I recently 
have been using it to create an algebraic type to hold a MYSQL value, so 
I can migrate the mysql-native library to be @safe (mysql-native 
currently uses Variant for everything).

I added a special UDA to TaggedAlgebraic, so you can guarantee only 
@safe calls are allowed (for instance, if it can hold a pointer and an 
int, then opBinary!"+" can be marked as @safe if the operation fails 
when it's a pointer).

TaggedAlgebraic could probably do the same for pure, but not sure about 
nothrow and @nogc, since it uses exceptions when things aren't valid.

-Steve


More information about the Digitalmars-d-learn mailing list