std.Algebraic alias this
Radu via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Oct 5 04:31:30 PDT 2015
There is a weird rule on how compiler treats alias this for the N
and S types bellow.
As you can see, somehow S losses it's type and ends up a plain
string withing the Algebraic type. I would expect that all types
should be the treated the same, why a string alias will be
different then a bool or a double?
int main(string[] argv)
{
import std.variant : Algebraic;
struct N { double val; alias val this; }
struct S { string val; alias val this; }
alias T = Algebraic!(N, S);
pragma(msg, T.AllowedTypes); // prints (N, string)??
T t = N(1.0);
assert(t.get!N == 1.0); // works
// t = 0.4; // fails, OK, variant.d(586): Error: static assert
"Cannot store a double in a VariantN!(8u, N, S). Valid types are
(N, string)"
// t = S("foo"); // this fails, why? Error: static assert
"Cannot store a S in a VariantN!(8u, N, S). Valid types are (N,
string)"
t = "bar"; // this works... why?
// assert(t.get!S == "bar"); //this fails Variant: attempting to
use incompatible types immutable(char)[] and main.main.S at
std\variant.d(1475)
assert(t.get!string == "bar"); // works, why?
return 0;
}
More information about the Digitalmars-d-learn
mailing list