Thread overview
Different typeof syntax
May 16, 2010
bearophile
May 16, 2010
Robert Clipsham
May 17, 2010
bearophile
May 16, 2010
Do you know if it's possible to replace  typeof(f1)  with  f1.typeof  in D (for symmetry with sizeof too)?

import std.stdio: writeln;
struct Foo {
    int x;
}
void main() {
    Foo f1;
    int fsize = f1.sizeof; // OK
    alias typeof(f1) T1;   // OK
    alias f1.typeof T2;    // ERR
}


[What I'd like is this, but this is for another thread:
Type T2 = f1.typeof;
]

Bye,
bearophile
May 16, 2010
On 16/05/10 21:43, bearophile wrote:
> Do you know if it's possible to replace  typeof(f1)  with  f1.typeof  in D (for symmetry with sizeof too)?
>
> import std.stdio: writeln;
> struct Foo {
>      int x;
> }
> void main() {
>      Foo f1;
>      int fsize = f1.sizeof; // OK
>      alias typeof(f1) T1;   // OK
>      alias f1.typeof T2;    // ERR
> }
>
>
> [What I'd like is this, but this is for another thread:
> Type T2 = f1.typeof;
> ]
>
> Bye,
> bearophile

The closest I've managed with my quick attempt is:
----
mixin template typeOf()
{
	alias typeof(this) typeOf;
}
struct Foo
{
	int x;
	mixin typeOf;
}
void main() {
    Foo f1;
    auto fsize = f1.sizeof; // OK
    alias typeof(f1) T1;   // OK
    alias f1.typeOf T2;    // OK
}
----

It's not ideal, but it works. You can choose a capitalization to suit you. If you want the capitalization to match you can make a similar template for sizeof to keep things consistent.

A couple of other things to note, I changed fsize to auto, as the type of .sizeof is different on x86_64, this isn't an issue now, but it's nice to keep code portable! Another thing is template bloat - I haven't looked properly, it seems that the template is optimized out though, so using it doesn't add any overhead... I could be wrong though.

Robert
May 17, 2010
Robert Clipsham:

> The closest I've managed with my quick attempt is:
> ----
> mixin template typeOf()
> {
> 	alias typeof(this) typeOf;
> }
> struct Foo
> {
> 	int x;
> 	mixin typeOf;
> }

Thank you for your code :-) Your example shows this feature can become a built-in.


> I changed fsize to auto, as the type of .sizeof is different on x86_64, this isn't an issue now, but it's nice to keep code portable!

You are right, thank you. At the moment it's a size_t, that is an unsigned CPU word. (I have recently asked in bugzilla for all those values to become signed words, because unsigned are too much unsafe in a language that doesn't catch signed-unsigned conversions and has no integral overflows tests).

Bye,
bearophile