D語言通過模板,很好的支援泛型程式設計。與C++的模板相比較,各有優略。總體上說,D語言的模板在很多方面還是很方便的。
D語言還支援模板的混入(mixin),簡單的講就是把模板執行個體化之後,將模板中的代碼插入到當前的位置。這是一個非常方便的工具!
具體的,請看下面的示範代碼。
import std.stdio;
void main()
...{
tryTemplate();
tryMixin();
}
// template
//---------------------------------------------
template MyMathLib(float_t)
...{
// struct, class模板
struct Vector2
...{
float_t x, y;
static Vector2 opCall(float_t _x, float_t _y)
...{
Vector2 ret;
ret.x = _x;
ret.y = _y;
return ret;
}
Vector2 opAdd(in Vector2 v)
...{
Vector2 ret;
ret.x = x + v.x;
ret.y = y + v.y;
return ret;
}
}
// 模板函數
float_t dot(in Vector2 v1, in Vector2 v2)
...{
return v1.x*v2.x + v1.y*v2.y;
}
}
// 函數模板的另外一種寫法
T Square(T)(T t)
...{
return t*t;
}
// 類模板的另外一種寫法
class Vector3(T)
...{
T x, y, z;
}
void tryTemplate()
...{
alias MyMathLib!(float).Vector2 Vector2f;
Vector2f v1 = Vector2f(1, 2);
Vector2f v2 = Vector2f(3, 4);
Vector2f v3 = v1 + v2;
writefln("x = ", v3.x, ", y = ", v3.y);
float d = MyMathLib!(float).dot(v1,v2);
writefln("d = ",d);
float f = 2;
f = Square(f); // 調用模板函數
writefln(f);
Vector3!(float) vv = new Vector3!(float);
}
// mixin
//-------------------------------
template MyMixin()
...{
void Foo()
...{
writefln("MyMixin.Foo");
}
}
template MyMixin2(T)
...{
T x;
}
class MyClass
...{
mixin MyMixin2!(int);
mixin MyMixin;
}
void tryMixin()
...{
MyClass c = new MyClass;
c.Foo();
writefln(c.x);
}