Using a string generated at compile-time in a @nogc function

Basile B via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 1 08:47:58 PDT 2016


On Sunday, 1 May 2016 at 13:22:27 UTC, Mithun Hunsur wrote:
> On Sunday, 1 May 2016 at 10:37:23 UTC, Anonymouse wrote:
>> On Sunday, 1 May 2016 at 05:28:36 UTC, Mithun Hunsur wrote:
>>> Hi all,
>>>
>>> I'm working on removing the string mixins from my code, but 
>>> have run into an issue:
>>>
>>> http://dpaste.dzfl.pl/ecd7eb53947e
>>>
>>> As far as I can tell, this should work; the enum should force 
>>> compile-time execution (which it does, as evidenced by the 
>>> pragma). [...]
>>
>> That does seem buggy but I don't know enough to say for 
>> certain. I'd suggest filing a bug report anyway; the worst 
>> thing that can happen is that it gets closed. Unreported bugs 
>> can only be fixed by accident.
>>
>> Tacking an .idup after .toLower seems to make it work, at 
>> least on dpaste (http://dpaste.dzfl.pl/8abed3d3ec6c). I would 
>> have thought both toLower and idup returned a normal string, 
>> but unsure.
>>
>>>         enum loweredName = member.to!string.toLower.idup;
>>>         pragma(msg, loweredName);
>>>
>>>         if (member == test)
>>>             return loweredName;
>
> Yup - that works. How odd! Along the same lines is
>
>     enum loweredName = "" ~ member.to!string.toLower;
>
> which also works without issues. This makes me think that the 
> result of `member.to!string.toLower` isn't being treated as a 
> string, despite being typed as one - and by using `idup` or 
> concatenating to it, we essentially retype it as a string.

Another solution:

----
import std.traits;
import std.conv;
import std.uni;
import std.stdio;

enum Test { A, B, C }

auto enumToString(Test test) @nogc nothrow
{
     @property string function() result = {return "";};
     foreach (member; EnumMembers!Test)
     {
	    if (member == test)
         {
             result = {return member.to!string.toLower;};
             break;
         }
     }
     return result;
}

void main()
{
	enumToString(Test.A)().writeln;
}
----

returns a delegate, although the call is quite unfriendly, 
despite of the @property.


More information about the Digitalmars-d-learn mailing list