Compile-time conversions from string to integer, real, etc.

Don Clugston dac at nospam.com.au
Fri Apr 13 12:21:39 PDT 2007


In std.metastring there are functions to convert integers to strings at 
compile time, but none to go the other way.
Floating point conversions are the worst; there are so many different 
formats, worrying about round-off error, etc. It's a total nightmare.
Luckily, this works...
<g>

/// Converts 'str' into a constant of type T.
/// str may contain any D expression which evaluates to a literal.
T evaluateLiteral(T, char [] str)()
{
     mixin("return " ~ str ~ ";"\n);
}

// Examples:
static assert(evaluateLiteral!(real, "1.234e-56") == 1.234e-56);
static assert(evaluateLiteral!(cdouble, "(8.45+56i)*36.2i") == 
(8.45+56i)*36.2i);
static assert(evaluateLiteral!(char [], `"abc"[1..2] ~ "def"`) == "bdef");



More information about the Digitalmars-d mailing list