DMD ver.0.149リリース
- Added limited support for implicit function template instantiation.
ついに暗黙の関数テンプレート実体化到来(条件付きではあるが)。いろいろと影響を及ぼしそうで激しく期待。
サンプルコードという名の車輪の再発明をしてみる。
max。
template max(T){
T max(T v1, T v2){
return (v1 > v2) ? v1 : v2;
}
}
max(10, 20) #=> 20
max(3.5, -1.2) #=> 3.5swap。
template swap(T){
void swap(inout T v1, inout T v2){
T tmp = v1; v1 = v2; v2 = tmp;
}
}
int a=1, b=2;
swap(a, b); #=> a=2, b=1
template bubbleSort(T){
void bubbleSort(inout T[] array){
for(int i=0; i<array.length-1; i++){
for(int j=array.length-1; j>i; j--){
if(array[j-1] > array[j])
swap(array[j-1], array[j]);
}
}
}
}
static int[] array = [4, 2, 5, 3, 1];
bubbleSort(array); #=> array=[1, 2, 3, 4, 5]transform。
template transform(T){
void transform(inout T[] array, void function(inout T) opr){
foreach(inout T val; array)
opr(val);
}
}
void increment(inout int i){
i++;
}
static int[] array = [1, 2, 3, 4, 5];
transform(array, &increment); #=> array=[2, 3, 4, 5, 6]
// 無名関数もOK
transform(array, function void(inout int i){ printf("[%d]", i); }); #=> [2][3][4][5][6]