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

时间:2013-09-12 10:25:10

标签: c++ templates

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

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

以下是代码:

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的含义是什么? index是像vector这样的容器吗?

为什么他会覆盖运营商?

1 个答案:

答案 0 :(得分:2)

  

index < dim && index >= 0的含义是什么?

如果true小于index且大于或等于零,则评估为dim

  

index是一个像vector这样的容器吗?

不,它是一个整数,用作数组的索引_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将为false。