better assertions and __FILE__ (compile time functions)
Lutger
lutger.blijdestijn at gmail.com
Mon Aug 20 04:42:45 PDT 2007
Bruce Adams wrote:
...
> I can see from using a variant of your example that is possible now.
> I forgot we had CTFE. I was surprised it allows arbitrary strings to be compiled as I though mxins were supposed to use code segments that have been parsed already.
> Anyway, I'm still struggling a bit with it. My main problem can be boiled
> down to the following example.
>
> char[] int2str(int foo_)
> {
> return std.metastrings.ToString!(foo_);
> }
This is almost correct, see below.
> char[] int2str(int foo_)
> {
> return std.metastrings.ToString(foo_);
> }
std.metastrings.ToString is a template, which must be instanciated with
!, so this is not correct.
My example was bad, I'm sorry, it didn't break because I only used these
__LINE__ and __FILE__ tokens. At the very bottom of
http://www.digitalmars.com/d/function.html the reason is explained:
"Any functions that execute at compile time must also be executable at
run time. The compile time evaluation of a function does the equivalent
of running the function at run time. "
For int2str, this is not the case. If you only need compile time
execution, you can rewrite these functions as templates. For my original
example:
template assertEqual(char[] actual, char[] expected)
{
const char[] assertEqual = `if (` ~ actual ~ `!=` ~ expected ~ `) { `
`writefln("Equality assertion failed in " ~ __FILE__ ~
" at line " ~ std.metastrings.ToString!(__LINE__));`
`writefln("expected value: '", ` ~ expected ~ `, "'");`
`writefln("actual value: '", ` ~ actual ~ `, "'");`
`assert(false);}`;
}
mixin(assertEqual!("foo","bar"));
> Incidentally is there a way of specifying you only want a function to be evaluated at compile time? Perhaps the static keyword?
> My plan when this kind of thing comes up is to have one function for
> the run-time portion and a seperate code generator for the compile time stuff.
See the eval template also at http://www.digitalmars.com/d/function.html
To determine whether a parameter is a constant or not (for dispatching),
perhaps one could use is-expressions to try to take the adress: is(
typeof(&arg)). That should evaluate to false for constants (at compile
time), but true for run-time parameters. Haven't tested it though.
More information about the Digitalmars-d-learn
mailing list