新增AI编程课程,引领技术教育新趋势
# ifdef HIGHPRECISION //set the high precision using norm_t = long double; # elif(defined LOWPRECISION) //set the low preciionusing norm_t = float; # elseusing norm_t = double; //default precision # endif //set precision
假设我现在有一个int的三维向量,我想要返回一个实数精度(norm_t)的单位化向量,于是我们写了一个成员函数vec3<norm_t> ret_unit()const,我们在主函数中需要创建一个vec3去接收ret_unit的返回值
那么,我们两手一摊,无可奈何你可能这样做:
vec3<??> normal = intV.ret_unit();
你可能做不到,??可能是vec3::norm_t 吗,显然不是,vec3是一个模板,只能先将vec3<T>中的T特化。突然觉得,模板类中公开公布了精度类型norm_t,但是却用不上??
解决方案
综合考量到其他类可能也需要精度设定,所以干脆把这设置部分代码单独出来,然后将norm_t 改名为precision,于是问题就解决了
模板类中只需要提前预处理precision文件即可进行如下简单定义:
using norm_t = precision;而主函数中也方便多了
vec3<precision> normal = intV.ret_unit();
<2>参数类型
我看过glm数学库的源码有一类函数是这么实现的
template <typename T, precision P> template <typename U> GLM_FUNC_QUALIFIER tvec3<T, P> & tvec3<T, P>::operator+=(tvec3<U, P> const & v) { this->x += static_cast<T>(v.x); this->y += static_cast<T>(v.y); this->z += static_cast<T>(v.z); return *this; }
其实,意思就是它允许+=另外一种类型的向量,然后我都强转到自身类型T之后进行运算
解决方案