如何定义它可以拥有任意参数的模板类

How to define a template class which it can owns arbitrary parameters?

本文关键字:参数 任意 拥有 何定义 定义      更新时间:2023-10-16

这个问题是在我阅读 Obj 模型第 1 章时出现的C++举一个我无法理解的例子。

作者想要定义一个模板类,该类的类型和坐标数都可以控制。

这是代码:

template < class type, int dim >
class Point
{
public:
   Point();
   Point( type coords[ dim ] ) {
      for ( int index = 0; index < dim; index++ )
         _coords[ index ] = coords[ index ];
   }
   type& operator[]( int index ) {
      assert( index < dim && index >= 0 );
      return _coords[ index ]; }
   type operator[]( int index ) const
      {   /* same as non-const instance */   }
   // ... etc ...
private:
   type _coords[ dim ];
};
inline
template < class type, int dim >
ostream&
operator<<( ostream &os, const Point< type, dim > &pt )
{
   os << "( ";
   for ( int ix = 0; ix < dim-1; ix++ )
      os << pt[ ix ] << ", ";
   os << pt[ dim-1 ];
   os << " )";
}

index < dim && index >= 0是什么意思?索引是一个类似 Vector 的容器?

他为什么要覆盖操作员?

index < dim && index >= 0是什么意思?

如果index小于 dim 且大于或等于零,则计算结果为 true

索引是像矢量一样的容器?

不,它是一个用作数组索引的整数,_coords .有效索引为 0、1、...、dim-1 ,因此断言会检查index是否在该范围内。

他为什么要覆盖操作员?

因此,您可以使用[]来访问点的组件,就好像它本身是一个数组一样。

Point<float, 3> point; // A three-dimensional point
float x = point[0];    // The first component
float y = point[1];    // The second component
float z = point[2];    // The third component
float q = point[3];    // ERROR: there is no fourth component

其中每个都调用重载运算符。最后一个将使断言失败;具体来说,index将是 3,dim也将是 3,所以index < dim将是假的。