Function that calculates in compile time when it can
Artur Skawina
art.08.09 at gmail.com
Wed Aug 8 02:32:19 PDT 2012
On 08/07/12 19:43, Marco Leise wrote:
> Am Mon, 06 Aug 2012 14:21:37 +0200
> schrieb "Minas Mina" <minas_mina1990 at hotmail.co.uk>:
>
>> 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).
>
> That's easy: http://dpaste.dzfl.pl/521f47a0
It's not a function, but a template - meaning not only does it require
a different syntax, but also that it can only be used with literals and
symbols. Ie 'fib!(expression_not_evaluable_at_ct)' like 'fib!(variable+1)'
will fail to compile.
artur
PS. Your code does not work with older compilers (like the 2.057 based
gdc that i'm using); this version works and is also more readable:
template isSymbol(alias S) {
enum isSymbol = __traits(compiles, __traits(parent, S));
}
template fib(alias N) {
static if (isSymbol!N) {
@property typeof(N+N) fib(typeof(N) N = N) {
return N<2 ? N : fib(N-1)+fib(N-2);
}
}
else {
static if (N<2)
alias N fib;
else
enum fib = fib!(N-1)+fib!(N-2);
}
}
More information about the Digitalmars-d-learn
mailing list