Thread overview
Contextual metaprogramming, query the parent type.
Feb 04, 2022
Nick Treleaven
Feb 04, 2022
Nick Treleaven
February 04, 2022

Let's say you create a type for constrained integers so that Int!(-2,128) can only hold values in the range [-2,128]. The Int type then has to decide whether it should store this in a ubyte with a -2 adjustment or store it in an short. Basically a space vs speed tradeoff.

In this situation the parent struct holding a field of the Int!(-2,128) type might provide information about this, but explicitly doing an Int!(-2,128, Context) is tedious.

So, what if you could write a template that queries the containing type and then either produces IntFast!(-2,128) or IntCompact!(-2,128) types?

Seems to me that this should be possible and could make metaprogramming more powerful, but I don't think it is possible now? Or am I wrong?

February 04, 2022

On Friday, 4 February 2022 at 09:41:57 UTC, Ola Fosheim Grøstad wrote:

>

So, what if you could write a template that queries the containing type and then either produces IntFast!(-2,128) or IntCompact!(-2,128) types?

I think you can do this but users would need to use a string mixin when defining the field. A function can obtain the parent symbol name using this trick:

string fieldString(string parentName = __traits(parent, {}).stringof){
   ...
} 
struct Parent
{
    mixin(fieldString);
}
February 04, 2022

On Friday, 4 February 2022 at 15:56:05 UTC, Nick Treleaven wrote:

>

I think you can do this but users would need to use a string mixin when defining the field. A function can obtain the parent symbol name using this trick:

Sorry, that doesn't work. But hopefully you get the idea - the string mixin produces something that obtains the parent type name:

struct Parent
{
    pragma(msg, __traits(parent, {}).stringof); // Parent
}
February 05, 2022

On Friday, 4 February 2022 at 16:03:08 UTC, Nick Treleaven wrote:

>

Sorry, that doesn't work. But hopefully you get the idea - the string mixin produces something that obtains the parent type name:

struct Parent
{
    pragma(msg, __traits(parent, {}).stringof); // Parent
}

Thanks, now I have something to tinker with. :)