Templates and stringof...

David Nadlinger see at klickverbot.at
Sat Aug 4 01:53:18 PDT 2012


On Saturday, 4 August 2012 at 03:07:21 UTC, Era Scarecrow wrote:
>> This can't work in general. What should such a function 
>> return? The fully qualified name, I.e. including packages and 
>> modules? What is if the referred to entity is a nested 
>> function/local variable? What is if it is defined in a module 
>> which is not imported in the place where the string is mixed 
>> in?
>
>  I would think, the exact 'text' of the way the variable was 
> called, in my example it would be "inum.i", and since it would 
> be at the local level (where the mixin was called) it should 
> have access to everything that it did at that time.

How do you determine what the »local level« is? A string mixin 
isn't something you can »call«, just a compile-time constant 
string, which can be »evaluated« in a completely different 
place than it can be constructed. Maybe some heuristic could be 
used, but it's not worth the trouble, in my opinion.

>  True I can add asserts as part of the output code, but as 
> mentioned hopefully the constraints could do that work, plus 
> adding extra checks as part of a mixin seems a little...  
> excessive, dirty and ugly.

Why would it be dirty? String mixins are just compile-time code 
generation. Also, using template constraints has almost zero 
benefits if overload resolution is not involved anyway – 
remember, this is just about the helper function/template 
generating the string to be mixed in.

>  Then doesn't it seem like we're missing a potentially 
> important piece of the puzzle for mixins and templates? very 
> likely my modified template will include you including the same 
> variable twice, but if someone gets lazy then it may not work.

As I said, there are almost always ways to achieve what you want 
without resorting to getting the string representation of an 
alias parameter. For example:

---
mixin template BitfieldsOn(alias target, <…>) if 
(isIntegral!(typeof(target))) {
     mixin({
         string code;
         // Generate code using "target" as identifier.
         return code;
     }());
}

mixin BitfieldsOn!(foo, <…>);
---

David


More information about the Digitalmars-d mailing list