Memoization in compile-time

weaselcat via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 13 06:16:26 PDT 2015


On Friday, 13 March 2015 at 12:49:48 UTC, Dennis Ritchie wrote:
> On Friday, 13 March 2015 at 02:38:18 UTC, Rikki Cattermole 
> wrote:
>> You could assign it to e.g. an enum. Or force it over using 
>> meta-programming.
>
> And this code can be rewritten to D?
>
> template <int n>
> struct Factorial
> {
>     enum { value = n * Factorial<n - 1>::value };
> };
>
> template <>
> struct Factorial<0>
> {
>     enum { value = 1 };
> };
>
> int main()
> {
>     constexpr auto x = Factorial<5>::value;
>     constexpr auto y = Factorial<7>::value;
> }

confusingly, D uses enum for named compile-time constants.
http://ddili.org/ders/d.en/enum.html

If you take Rikki's example and apply it to an enum(i.e,
enum x = factorial(5);
)

the program will fail to compile if it can't be computed at 
compile-time.


More information about the Digitalmars-d-learn mailing list