Compile time string parse

Jarrett Billingsley jarrett.billingsley at gmail.com
Tue Mar 17 08:32:13 PDT 2009


On Tue, Mar 17, 2009 at 11:28 AM, Jarrett Billingsley
<jarrett.billingsley at gmail.com> wrote:
> On Tue, Mar 17, 2009 at 10:54 AM, Paolo Invernizzi
> <arathorn at fastwebnet.iit> wrote:
>> Hi all,
>> Someone can point me to a way of doing something like this with DMD 2.026:
>>
>> class A {
>>    invariant(int) rev = std.conv.to!(int)("$Rev: 182 $");
>> }
>>
>> I've messed up with metastrings and std.conv, but I cannot find a working way.
>>
>> Cheers, Paolo
>>
>
> int parseRevision(string s)
> {
>        // I'm assuming it'll always be of the form "\$ Rev: (\d+) \$"
>        return to!(int)(s["$ Rev: ".length .. $ - 2]);
> }
>
> void main()
> {
>        immutable(int) x = parseRevision("$ Rev: 182 $");
>        writefln(x);
> }

Oh, oops, didn't notice it was in a class.

template Atoi(string s)
{
	static if(s.length == 1)
		enum int Atoi = s[0] - '0';
	else
		enum int Atoi = 10 * Atoi!(s[0 .. $ - 1]) + (s[0] - '0');
}

template parseRevision(string s)
{
	// I'm assuming it'll always be of the form "\$ Rev: (\d+) \$"
	enum parseRevision = Atoi!(s["$ Rev: ".length .. $ - 2]);
}

class A
{
	immutable(int) x = parseRevision!("$ Rev: 182 $");
}


More information about the Digitalmars-d-learn mailing list