Thread overview
Determine type of property
Feb 02, 2016
tsbockman
Feb 02, 2016
NX
February 01, 2016
S has 3 different properties, x, y, z:

struct S
{
   int x;
   int y() { return 1;}
}

int z(S s) { return 1;}

pragma(msg, typeof(S.init.x).stringof); // int
pragma(msg, typeof(S.init.y).stringof); // int()
pragma(msg, typeof(S.init.z).stringof); // int

Is there a trait I can call/use to consistently get "int" from all 3?

-Steve
February 02, 2016
On Tuesday, 2 February 2016 at 03:36:25 UTC, Steven Schveighoffer wrote:
> S has 3 different properties, x, y, z:
>
> struct S
> {
>    int x;
>    int y() { return 1;}
> }
>
> int z(S s) { return 1;}
>
> pragma(msg, typeof(S.init.x).stringof); // int
> pragma(msg, typeof(S.init.y).stringof); // int()
> pragma(msg, typeof(S.init.z).stringof); // int
>
> Is there a trait I can call/use to consistently get "int" from all 3?
>
> -Steve

import std.traits, std.stdio;

alias PropertyType(T, string property) =
	ReturnType!(function(T x) { return mixin("x." ~ property); });

struct S
{
   int x;
   int y() { return 1;}
}

int z(S s) { return 1;}

void main() {
	writeln(PropertyType!(S, "x").stringof);
	writeln(PropertyType!(S, "y").stringof);
	writeln(PropertyType!(S, "z").stringof);
}

(DPaste: http://dpaste.dzfl.pl/0b03bc8ea11f)
February 02, 2016
On Tuesday, 2 February 2016 at 03:36:25 UTC, Steven Schveighoffer wrote:
> int y() { return 1;}

No need for meta-programming hackery, mark it as @property:

int y() @property { return 1;}

February 02, 2016
On 2/2/16 2:04 PM, NX wrote:
> On Tuesday, 2 February 2016 at 03:36:25 UTC, Steven Schveighoffer wrote:
>> int y() { return 1;}
>
> No need for meta-programming hackery, mark it as @property:
>
> int y() @property { return 1;}
>

I don't have control over S. I am passed S and need to figure out that it qualifies as a type I can use.

I also figured this out on my own, but for some reason my reply didn't go through. This is what I came up with:

template propertyType(alias x)
{
    static if(is(typeof(x) == function))
        alias propertyType = typeof(x());
    else
        alias propertyType = typeof(x);
}

-Steve