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

标签 c++ templates

这个问题是在看C++ Obj model,chapter 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之类的容器?

他为什么要覆盖运算符(operator)?

最佳答案

what does index < dim && index >= 0 means?

它的计算结果为 true如果index小于 dim并且大于或等于零。

index is a container like vector?

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

why did he override the operator?

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

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将是错误的。

关于c++ - 如何定义一个可以拥有任意参数的模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18761713/

相关文章:

c++ - 如何从带有 PR_BODY_A 标签的 MAPI 消息中获取编码 (windows mobile)?

c++ - 线程安全的 PQconn 对象

c++ - 通过调用 constexpr 函数定义静态 constexpr 成员

c++ - noexcept 和模板可能存在的 g++ 错误

c++ - 自定义静态分配器可能吗?/一种伪造它的方法?

c++ - 模板(元)编程是否总是只有一种实现方式?

c++ - 将父类(super class)函数作为非类型名模板参数传递

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

c++ - 模板中的运算符重载

c++ - 重载 'min(int&, int&)' 的调用不明确