雖然它不適合任何情況,模板可以給你「編譯時鴨子打字」。
比方說你有兩個載體類型:
struct Vec3A {
float x, y, z;
};
struct Vec3B {
float p[3];
};
您可以定義隱藏實現的如何獲得組件函數模板:
template<class T> float get_x(const T&);
template<class T> float get_y(const T&);
template<class T> float get_z(const T&);
template<> float get_x<Vec3A>(const Vec3A& v) { return v.x; }
// ...
template<> float get_x<Vec3B>(const Vec3B& v) { return v.p[0]; }
// ...
有了這樣的助手,你現在就可以編寫通用可以在兩者上工作的功能:
template<class T> float length(const T& t) {
return std::sqrt(std::pow(get_x(t), 2),
std::pow(get_y(t), 2),
std::pow(get_z(t), 2));
}
您還可以繼續e出於性能或其他原因通過專門使用諸如length()
等實用程序,例如如果某一矢量已經有一個成員函數爲您提供長度:
template<> float length<Vec3C>(const Vec3C& v) {
return v.length();
}
我錯過了什麼嗎?爲什麼用OCaml標記? – 2010-06-02 21:07:11
[ocaml]標記已刪除 – Thelema 2010-06-09 23:01:20