C ++ Inheritance / Template Question

I have two classes: dot and pixel:

class point {
    public:
        point(int x, int y) : x(x), y(y) { };
    private:
        int x, y;
}

template <class T>
class pixel : public point {
    public:
        pixel(int x, int y, T val) : point(x, y), val(val) { };
    private:
        T val;
}

Now here is my problem. I want to create a container class (let it be called coll) that has a private vector of dots or pixels. If the coll instance contains pixels, I want it to have a toArray () method that converts the vector of the vector to an array from T representing the contents of the vector.

I was going to do this with inheritance: i.e. I could create a base class coll containing a point vector and a derived class that contains an extra method, but then I seem to run into problems, since a pixel is a template class.

Does anyone have any suggestions? Can I do this somehow by creating a class template?

+5
3

: , , ?

: , ?

, Point Pixel , - :

template < class T > class CollectionBase
{
   //common interface here
   protected:
   std::vector<T> coll_vec;
};

class PointCollection : public CollectionBase<Point>
{
   public:
   ...
};

template< class T> PixelCollection : public CollectionBase<Pixel<T> >
{
   public:
    Pixel<T>* toArray();

    ...

};
+3

, point pixel<T>, , dynamic_cast NULL. point , .

:

point x(0, 0);
pixel<int> y(0, 0, 0);
point *pX = &x;
point *pY = &y;
if(dynamic_cast<pixel<int> *> (pX) != NULL) {
    std::cout << "x is a pixel<int>.";
}
if(dynamic_cast<pixel<int> *> (pY) != NULL) {
    std::cout << "y is a pixel<int>.";
}

:

y - <int> .

coll, , vector<point *> . , (.. pixel<int> pixel<float>?)

coll .

+1

collection point pixel , .
to_array, :

template<class T> struct collection {
    std::vector<point<T> > data_;
    // ...
};

template<class T>
void to_array(const collection<point<T> >& in, point<T>* out) {
    // ...
}

, to_array() .

+1

All Articles