template functions, a special case of constant folding?
Deewiant
deewiant.doesnotlike.spam at gmail.com
Fri Mar 24 07:49:32 PST 2006
Hasan Aljudy wrote:
>> If it's too hard to make the compiler smart enough, then maybe we can
>> add a keyword to hint to the compiler that if all arguments to this
>> function are constants then it can be "folded"!
>> After all, that's essentially what the "template" keyword is doing!
>> (kinda, not really though, I know).
>>
>> # fold int add( int x, int y ) { return x + y; }
>> vs.
>> # template add( int x, int y ) { const add = x + y; }
>>
>> The "fold" version of the function can be reused for non-constant
>> arguments. Where as the templated version can't. (although I'm not
>> entirely sure about that).
>>
I'd use something like this syntax, borrowed from C++:
int add(int x, int y) const { return x + y; }
The key here being "const". The function has no side effects, and given the same
arguments always returns the same answer. This construct is one of the few I
miss from C++, although what I'm talking about might be a bit different - I
can't remember, it's been a while since I've done a lot in C++.
This would require the following demands of const functions - they cannot:
- contain static variables,
- call non-const functions,
- refer to non-const variables defined outside their own scope.
And probably something else, too, that I forgot or couldn't think of.
I'm not sure how pointers would fit into the above, though. Should const
functions be able to use pointers at all? Only class pointers (which aren't,
syntax-wise, pointers per se)? How does it work in C++?
Const functions should basically fit the bill for what you're asking for,
although it requires some work from the compiler as well, since it has to check
whether you're really right about the constness - or "foldability" as you might
call it - by enforcing the above criteria.
More information about the Digitalmars-d
mailing list