|
Revision 254, 1.3 kB
(checked in by pragma, 2 years ago)
|
--
|
| Line | |
|---|
| 1 |
/** |
|---|
| 2 |
*/ |
|---|
| 3 |
module meta.generatetable; |
|---|
| 4 |
|
|---|
| 5 |
private import meta.hack.hackgenerate; |
|---|
| 6 |
|
|---|
| 7 |
/** T [] generateArray!( T function!(int) generator, int n) |
|---|
| 8 |
* Generate a lookup table |
|---|
| 9 |
* |
|---|
| 10 |
* Returns the constant array [ generator!(0), generator!(1),.. generator!(n)] |
|---|
| 11 |
* Params: |
|---|
| 12 |
* generator The name of a metafunction template which takes a single integer parameter, |
|---|
| 13 |
* and returns a constant value of arbitrary type. generator!(0) |
|---|
| 14 |
* must be valid. |
|---|
| 15 |
* It must be a template name, not a template instance. |
|---|
| 16 |
* n The highest entry to generate. It must be between 0 and 127, inclusive. |
|---|
| 17 |
* |
|---|
| 18 |
* Example: |
|---|
| 19 |
* Here, the computationally expensive factorial function is completely moved to compile |
|---|
| 20 |
* time. |
|---|
| 21 |
---- |
|---|
| 22 |
// Returns correct value for n=0 (factorial(0)=1). |
|---|
| 23 |
template factorial(uint n) |
|---|
| 24 |
{ |
|---|
| 25 |
static if (n<2) const ulong factorial = 1; |
|---|
| 26 |
else const ulong factorial = n * factorial!(n-1); |
|---|
| 27 |
} |
|---|
| 28 |
|
|---|
| 29 |
// Make an array of all the factorials from 0 to 20. |
|---|
| 30 |
const ulong [] smallfactorials = generateLookupTable!(factorial, 20); |
|---|
| 31 |
|
|---|
| 32 |
ulong factorial(uint n) |
|---|
| 33 |
{ |
|---|
| 34 |
assert(n<=20); |
|---|
| 35 |
return smallfactorials[n]; |
|---|
| 36 |
} |
|---|
| 37 |
----- |
|---|
| 38 |
*/ |
|---|
| 39 |
template generateArray(alias generator, int n) |
|---|
| 40 |
{ |
|---|
| 41 |
const typeof(generator!(0)) [] generateArray = hackgenerate!(n, generator); |
|---|
| 42 |
} |
|---|