(emulating) weak typing and some other things

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Dec 20 10:18:54 PST 2013


On Fri, Dec 20, 2013 at 09:40:47AM -0800, H. S. Teoh wrote:
> On Fri, Dec 20, 2013 at 06:30:53PM +0100, seany wrote:
> > I am sorry, perhaps the question could be answered with already
> > available information, but I did not manage to figure it completely
> > 
> > I realize that D is a strongly typed language. But in certain
> > scenarios i may want to use a weak typing, especially when handling
> > structs which are very close to each other in content, but not equal,
> > it would be nice to use to redefine the type while preserving the
> > name.
> [...]
> 
> See std.typecons.Variant.
[...]

Another way is to use alias this:

	struct B {
		int x, y, z; // common fields
	}

	struct C {
		B _common;
		alias _common this;

		float p, q, r;
	}

	struct D {
		B _common;
		alias _common this;

		string a, b, c;
	}

	C c;
	c.x = 1; // same as c._common.x = 1
	c.p = 1.0;

	D d;
	d.x = 1; // same as d._common.x = 1
	d.a = "abc";

	void fun(B b) { ... }

	fun(c); // OK, same as fun(c._common)
	fun(d); // OK, same as fun(d._common)

Basically, this is the struct equivalent of class inheritance, except
without the dynamic polymorphism.

If this is not good enough, you can use casts to force structs into each
other:

	struct S {
		int x;
		string y;
	}

	struct T {
		int a;
		float b;
	}

	T t;
	S* ptr = cast(S*) &t;
	ptr.x = 1; // effectively does t.a = 1.

But this is dangerous, since it relies on programming by convention: if
the definitions of S and T don't match, the above code will corrupt data
instead.  Using alias this or std.typecons.Variant is a much better,
type-safe solution.


T

-- 
Claiming that your operating system is the best in the world because more people use it is like saying McDonalds makes the best food in the world. -- Carl B. Constantine


More information about the Digitalmars-d-learn mailing list