Mario Gil
Mario Gil

Reputation: 563

How to handle a vector of template class?

i'm working on a quicksort function that sorts a vector of objects created from a template. Specifically a vector of Points on a n dimention space. This is my Point template:

#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
//-----------

This is the quicksort function (i haven't written the actual implementation because i wish to solve this problem first):

#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 --------------

The errors i'm getting (some of them):

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> >

I would appreciate if you can point where i'm wrong, any tips or ideas are welcome, i'm sort of a self-taught programmer. Thanks.

Upvotes: 1

Views: 262

Answers (2)

Lochemage
Lochemage

Reputation: 3974

Your quicksort definition should just declare its template like this:

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

whenever you call quicksort, you add the template for your particular Point setup:

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

As per Mooing Duck's comment, in this case, you don't need to supply your template type as it can be deduced by the compiler:

quicksort(pointList);

should be all you need.

Upvotes: 0

jwodder
jwodder

Reputation: 57470

Because quicksort can operate on vector<Point<int dimention, typename type> > for any values of dimention and type, it is a template function and must be declared as such:

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

Also note that the int and typename in Point<dimention, type> are removed here.

Upvotes: 2

Related Questions