C++继承/模板问题

amc*_*amc 5 c++ oop inheritance templates

我有两个类,点和像素:

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;
}
Run Code Online (Sandbox Code Playgroud)

现在这是我的问题.我想创建一个容器类(让我们称之为coll),它有一个点或像素的私有向量.如果coll的实例包含像素,我希望它有一个方法toArray(),它将像素向量转换为表示向量内容的T数组.

我将继承这样做:即,我可以创建一个包含点向量的基类coll和包含额外方法的派生类,但是我似乎遇到了问题,因为像素是一个类模板.

有没有人有建议?我可以通过使coll成为类模板来实现这一点吗?

div*_*a23 3

问题:您的意思是私有向量同时包含点和像素,还是仅包含其中之一?

问题:如果只是其中之一,您是否打算在同一私有向量中混合具有不同模板参数的像素?

假设它只是私有向量中的点或像素,并且私有向量中的像素都具有相同的模板参数,您可以执行以下操作:

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();

    ...

};
Run Code Online (Sandbox Code Playgroud)