www.digitalmars.com         C & C++   DMDScript  

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

reply Don Clugston <dac nospam.com.au> writes:
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");
Apr 13 2007
parent reply Walter Bright <newshound1 digitalmars.com> writes:
Don Clugston wrote:
 In std.metastring there are functions to convert integers to strings at 
 compile time,
Can these be replaced with .stringof ?
Apr 13 2007
parent reply Don Clugston <dac nospam.com.au> writes:
Walter Bright wrote:
 Don Clugston wrote:
 In std.metastring there are functions to convert integers to strings 
 at compile time,
Can these be replaced with .stringof ?
Yup. It should probably be wrapped in a deprecated{} now. As should std.math2.
Apr 13 2007
parent reply Don Clugston <dac nospam.com.au> writes:
Don Clugston wrote:
 Walter Bright wrote:
 Don Clugston wrote:
 In std.metastring there are functions to convert integers to strings 
 at compile time,
Can these be replaced with .stringof ?
Yup. It should probably be wrapped in a deprecated{} now. As should std.math2.
For example: template toString(real x) { const char [] toString=x.stringof; } Unfortunately, none of these work inside a CTFE function. The problem is, that a CTFE function has to also work at runtime, and so it can't use compile-time variables in template value arguments (and it can't index tuples, etc). These kinds of operations are the only ones where template metaprogramming still survives.
Apr 13 2007
parent Walter Bright <newshound1 digitalmars.com> writes:
Don Clugston wrote:
 For example:
 
 template toString(real x)
 {
     const char [] toString=x.stringof;
 }
 
 Unfortunately, none of these work inside a CTFE function. The problem 
 is, that a CTFE function has to also work at runtime, and so it can't 
 use compile-time variables in template value arguments (and it can't 
 index tuples, etc). These kinds of operations are the only ones where 
 template metaprogramming still survives.
I think AST macros should take care of this problem.
Apr 13 2007