www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Contextual metaprogramming, query the parent type.

reply Ola Fosheim =?UTF-8?B?R3LDuHN0YWQ=?= <ola.fosheim.grostad gmail.com> writes:
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?
Feb 04 2022
parent reply Nick Treleaven <nick geany.org> writes:
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: ```d string fieldString(string parentName = __traits(parent, {}).stringof){   ... }  struct Parent {    mixin(fieldString); } ```
Feb 04 2022
parent reply Nick Treleaven <nick geany.org> writes:
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: ```d struct Parent { pragma(msg, __traits(parent, {}).stringof); // Parent } ```
Feb 04 2022
parent Ola Fosheim =?UTF-8?B?R3LDuHN0YWQ=?= <ola.fosheim.grostad gmail.com> writes:
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:

 ```d
 struct Parent
 {
     pragma(msg, __traits(parent, {}).stringof); // Parent
 }
 ```
Thanks, now I have something to tinker with. :)
Feb 05 2022