如何处理模板类的向量

How to handle a vector of template class?

本文关键字:向量 何处理 处理      更新时间:2023-10-16

我正在研究一个快速排序函数,该函数对从模板创建的对象向量进行排序。特别是n维空间上的点向量。这是我的Point模板:

#ifndef POINT_H   
#define POINT_H   
template <int dimention, typename type>   
class Point{
public:
    Point(){mCoords = new type[dimention];}
    Point(type* pCoords);
    int getDimention(){return dimention;}
// Operators
//-----------

这是快速排序函数(我还没有写实际的实现,因为我想先解决这个问题):

#ifndef QUICK_S
#define QUICK_S
#include <vector>
#include "point.h"
// Generic quicksort function that works with points of any dimention
std::vector<Point<int dimention, typename type> > 
quicksort(std::vector<Point<int dimention, typename type> > unsorted)
{
// implementation --------------

我得到的错误(其中一些):

In file included from convexHull.cpp:4:0:
quicksort.h:7:47: error: wrong number of template arguments (1, should be 2)
In file included from quicksort.h:4:0,
             from convexHull.cpp:4:
point.h:5:7: error: provided for ‘template<int dimention, class type> class Point’
 class Point{
In file included from convexHull.cpp:4:0:
quicksort.h:7:49: error: template argument 1 is invalid
std::vector<Point<int dimention, typename type> >
如果你能指出我错的地方,我会很感激,任何建议或想法都是受欢迎的,我是一个自学成才的程序员。谢谢。

因为quicksort可以对dimentiontype的任何值对vector<Point<int dimention, typename type> >进行操作,所以它是一个模板函数,必须这样声明:

template<int dimention, typename type>
std::vector<Point<dimention, type> > 
quicksort(std::vector<Point<dimention, type> > unsorted)

还要注意,Point<dimention, type>中的inttypename在这里被删除了。

你的快速排序定义应该像这样声明它的模板:

std::vector<typename type> 
quicksort(std::vector<type> unsorted)
{
// implementation --------------

无论何时调用快速排序,都要为特定的点设置添加模板:

quicksort<Point<1,float> >(pointList);

根据Mooing Duck的注释,在这种情况下,你不需要提供你的模板类型,因为它可以由编译器推断出来:

quicksort(pointList);