虽然它不适合任何情况,但模板可以为您提供“编译时鸭子类型”。
假设您有两种矢量类型:
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));
}
您还可以通过专门化实用程序来继续,例如length()
出于性能或其他原因,例如,如果某个向量已经有一个成员函数为您提供长度:
template<> float length<Vec3C>(const Vec3C& v) {
return v.length();
}