to!string(double) at compile time

Philippe Sigaud philippe.sigaud at gmail.com
Thu Aug 23 06:55:55 PDT 2012


On Tue, Aug 21, 2012 at 6:43 AM, Bobby Bingham <uhmmmm at gmail.com> wrote:
> I'm just getting started with D, and was playing around with string
> mixins.  I've hit a snag, and have reduced it to a minimal test case:
>
>     import std.conv;
>
>     string test()
>     {
>         return to!string(0.0);
>     }
>
>     immutable auto testvar = mixin(test());
>

> I guess converting a double to a string can't be done at compile time
> because it requires calling the C snprintf function?  It compiles fine
> if I replace the 0.0 with an int literal.  Is there any way around
> this limitation?

A possibility is to use a function template, passing the double as a
template argument:

string test(double d)() // d is a template argument
{
    return d.stringof;
}

enum testvar = mixin(test!(3.14));

void main()
{
    pragma(msg, testvar);
}


More information about the Digitalmars-d-learn mailing list