Function that calculates in compile time when it can
Artur Skawina
art.08.09 at gmail.com
Mon Aug 6 07:57:38 PDT 2012
On 08/06/12 15:46, Tobias Pankrath wrote:
> On Monday, 6 August 2012 at 12:21:38 UTC, Minas Mina wrote:
>> I want to write a fibonacci(n) function that calculates the result.
>> a) if n is known at compile time, use a template
>> b) if not, use a normal function
>>
>> I know how to write a template version:
>> template fib(ulong n)
>> {
>> static if( n < 2 )
>> const fib = n;
>> else
>> const fib = fib!(n-1) + fib!(n-2);
>> }
>>
>> But how can I 'know' if n is known at compile time to make it use the other version? (which I won't post 'cause it is fairly easy).
>
> What exactly do you try to accomplish? Why can't you use CTFE instead of a template?
He wants the function to be evaluated at compile time if that is possible,
but at runtime if that can't be done; and *not* have to handle both cases
in every caller. Which I can't think of any way to do right now.
An "T fib(T)(enum T n)" overload that would enable cases like this (and
bearophiles ranged-integers) to work, has been proposed in the past (only
with 'static' instead of 'enum'; the latter fits better).
IOW a "fib(42)" call would map to more or less:
enum T c = 42;
fib(c);
and inside such an overload the argument 'n' would be treated just like if it
had been defined as:
enum T n = 42;
ie it would be cfte'able and /then/ static-if and friends would be able to
handle the rest.
artur
More information about the Digitalmars-d-learn
mailing list