使用具有模板基类的类作为基类参数

bit*_*ise 1 c++ inheritance arguments class vector

我在这里错过了什么吗?还是有理由不允许这样做?

// the class declaration
class MapImage : public MapEntity, public Vector2D {};

// the variable declaration
std::vector<MapImage> healthpacks;

// the function
void DrawItems(SDL_Surface *dest, std::vector<Vector2D> &items, SDL_Surface *image);

// the implementation
DrawItems(dest, healthpacks, healthpack_image);
Run Code Online (Sandbox Code Playgroud)

因为healthpacks是一个MapImage类的std :: vector,而MapImage有基类Vector2D,所以不应该"std :: vector healthpacks"与"std :: vector&items"兼容,因为它们具有相同的基类?

Fre*_*urk 5

不可以.基类的向量本身不是派生类向量的基类.

考虑DrawItems是否将一个Vector2D对象(一个不是 MapImage的对象)插入到项目中:你会在向量<MapImage>中有一些不是MapImage的东西.但是,由于DrawItems具有向量<Vector2D>,因此从其角度来看,该插入将是完全有效的.

相反,在迭代器上传递迭代器范围和模板:

void DrawItem(SDL_Surface *dest, Vector2D &item, SDL_Surface *image);

template<class Iter>
void DrawItems(SDL_Surface *dest, Iter begin, Iter end, SDL_Surface *image) {
  for (; begin != end; ++begin) {
    DrawItem(dest, *begin, image);
  }
}
Run Code Online (Sandbox Code Playgroud)

或者在容器上:

template<class Container>
void DrawItems(SDL_Surface *dest, Container &items, SDL_Surface *image) {
  typename Container::iterator begin = items.begin(), end = items.end();
  for (; begin != end; ++begin) {
    DrawItem(dest, *begin, image);
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,除了DrawItems,但仍然使用我上面声明的DrawItem,可能使用一个新的for-each循环:

// this: DrawItems(dest, healthpacks, healthpack_image);
// becomes:
for (auto &x : healthpack) DrawItem(dest, x, healthpack_image);
Run Code Online (Sandbox Code Playgroud)

它似乎你需要添加const,但我已经离开了代码,就像你拥有它一样.