Compile time function execution...
Walter Bright
newshound at digitalmars.com
Thu Feb 15 18:13:07 PST 2007
Bill Baxter wrote:
> Right. But if I understand correctly, the same code can get called
> either at runtime or compile time depending on the situation.
Yes.
> But what if I want the runtime version to print out a message. Or add
> to a global counter variable for some simple home-brew profiling stats.
> It would be handy then if I could do:
>
> int square(int x) {
> version(compiletime) {}else{
> writefln("trace: square");
> G_CallsToSquare++;
> }
> return (x*x);
> }
I see what you want, but it isn't going to work the way the compiler is
built. Runtime interpretation occurs *after* semantic analysis, but
versioning happens before. Right now, you're better off having two
functions, one a wrapper around the other.
After all, there isn't a version possible for inlining/not inlining, either.
> I think I'm getting at the same kind of thing Andrei is talking about. I
> don't want to have to limit what I do in the runtime version in order to
> make it acceptable for compile time. He's saying I should be able to
> have two versions of the function, one for compile time and one for run
> time. I think that's useful too. But for simpler cases like the above,
> it would be nice I think if one could just version-out the bad parts.
>
> And in this case:
>
> int calculationIShouldOnlyDoAtCompileTime(int x)
> {
> // * whatever it is *
> }
>
> int K = calculationIShouldOnlyDoAtCompileTime(4);
>
> Whoops! Silly programmer, looks like I forgot the 'const' on K. Would
> be nice if I could get the compiler to remind me when I'm silly like
> that. That could be arranged if there were a version(CompileTime).
For compile time evaluation only, make the function instead a template
that calls the function.
> For instance, it's not uncommon to make a fixed length vector class
> using templates. Vec!(N) kind of thing. But it would really be nice if
> the majority of that code could remain even when N is not constant. That
> means both on the user side and on the implementation side. I don't
> know how realistic that is, but I often find myself sitting on the fence
> trying to decide -- do I make this a compile-time parameter, thereby
> cutting off all opportunity for runtime creation of a particular
> instance, or do I make it runtime, thereby cutting my and the compiler's
> opportunity to make several obvious optimizations.
Templates are supposed to fill that ecological niche.
More information about the Digitalmars-d
mailing list