如何定义它可以拥有任意参数的模板类
How to define a template class which it can owns arbitrary parameters?
这个问题是在我阅读 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
将是假的。
相关文章:
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 具有任意数量参数的模板函数
- 将任意模板向量作为函数参数C++传递
- C++:任意函数作为函数的参数
- 如何在 C++ 中为任意数量的字符串串联编写可变参数函数
- 使用 std::function 作为具有任意数量参数的数据成员
- 使用模板将任意类型参数传递给 C++ 中的函数
- 使用来自C++的任意数量的参数(在编译时未知)调用 Python 函数
- C++具有模板成员的类,该类使用任意模板参数构造模板成员
- is_invocable使用任意函数参数类型
- 如何动态执行具有任意参数类型的函数指针
- Java函数在C++中具有任意数量的参数
- 使用 lambda 和可变参数模板延迟初始化对象 - 任意传递值
- 在 C++ 中使用 vector 传递任意数量的参数
- 如何为函数参数指定任意模板参数?
- lambda/任意Arity的功能和以捕获为函数参数的功能
- 将具有任意参数和占位符的函数存储在类中,然后再调用它
- 在C++中,是否可以将任意指针作为输入参数
- 使用模板类的任意数量的参数分配
- visual如何在C++中创建一个函数来提供任意数量的参数