digitalmars.D - Contextual metaprogramming, query the parent type.
- Ola Fosheim =?UTF-8?B?R3LDuHN0YWQ=?= (14/14) Feb 04 2022 Let's say you create a type for constrained integers so that
- Nick Treleaven (15/18) Feb 04 2022 I think you can do this but users would need to use a string
- Nick Treleaven (9/12) Feb 04 2022 Sorry, that doesn't work. But hopefully you get the idea - the
- Ola Fosheim =?UTF-8?B?R3LDuHN0YWQ=?= (2/11) Feb 05 2022 Thanks, now I have something to tinker with. :)
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
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
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
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