Library Typedefs are fundamentally broken

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Sep 18 11:00:18 PDT 2014


On Thu, Sep 18, 2014 at 05:48:30PM +0000, Wyatt via Digitalmars-d wrote:
[...]
> If you want those things to work, you have to wrap it in a struct and
> use alias this (which IS a legitimately cool application of the
> aliasing semantics, I'll grant).  This can be mitigated somewhat, but
> it still feels inelegant and not-D-like for something I'd really like
> to use easily and often.  Also, for the hardcore among you, I think
> your cache may hate you for this (I don't recall if that overhead gets
> optimised away).
[...]

Why would your cache hate you for it? A struct that contains, say, a
single int, is at the assembly level identical to the int itself,
because structs are value types and they were basically designed to be
"glorified ints", as Andrei puts it in TDPL. When you write something
like:

	struct S {
		int x;
		alias x this;
		// ...
	}

	S s;
	s++;

basically "s++" gets translated to "s.x++", and since S behaves
basically identically to an int, which means it should get enregistered
under the same circumstances, the generated machine code should be
identical to when you wrote "int" instead of "S".

I don't see why this should have any effect on the cache. Unless you
added extra fields to your struct where you shouldn't, and it becomes
too big to fit in registers, then it's not really the compiler's fault.
:-P

The neatest thing about this, is that any operator overloading you
implement for S will, in effect, behave like overloading the built-in
int operators; and if your operator overloads have simple
implementations, they will be inlined and you get basically a "native"
int but with overloaded operators. (This, of course, is the whole point
behind the 'checkedint' type currently used by some internal Phobos /
dmd functions. You basically have a type that's identical to int in
every way, except that some operations will have overflow checks
inserted in front in the machine code.)

This is why 'alias this' is such a total stroke of genius. It brings the
parity between user and built-in types to a whole new level of cool.


T

-- 
Curiosity kills the cat. Moral: don't be the cat.


More information about the Digitalmars-d mailing list