Re: Casting to union type?

2014-08-26 Thread via Digitalmars-d-learn

On Tuesday, 26 August 2014 at 02:33:25 UTC, cc wrote:

vec2 a = vec2(1.0, 2.0); // fine
vec2 b;
b = [3.0, 4.0]; //fine
vec2 c = [5.0, 6.0]; // cannot cast float[] to vec2


There is currently no implicit for aggregates except using `alias 
this`. But in your example, it's a construction, not an 
assignment, so you need to write an appropriate constructor 
`this(float[])` analogous to `opAssign(float[])`.


Re: Casting to union type?

2014-08-26 Thread cc via Digitalmars-d-learn
Ahh, thanks.  Looks like encapsulating the union in a struct with 
alias this gets the job done, and removes the need for overloads. 
 Neat.


struct vec2 {
union {
struct {
float x = 0.0f;
float y = 0.0f;
}
float[2] v;
}

this(float x, float y) {
this.x = x;
this.y = y;
}
this(float[v.length] f) {
v[0..length] = f[0..length];
}
alias v this;
}


Re: Casting to union type?

2014-08-25 Thread Jonathan M Davis via Digitalmars-d-learn

On Tuesday, 26 August 2014 at 02:33:25 UTC, cc wrote:

Is it possible to allow implicit casting from a base type to a
union type?


All implict conversions are done using alias this:

http://dlang.org/class.html#AliasThis

- Jonathan M Davis