苹果.h
class Apple {
public:
Apple(int);
static int typeID;
private:
int id_;
};
苹果.cpp
#include "Apple.h"
Apple::Apple(int pID) {
id_ = pID;
}
Potato.h、Potato.cpp 与 Apple 相同
存储.h
#pragma once
#include "Apple.h"
#include "Potato.h"
#include <vector>
class Storage {
public:
Storage();
template<typename foodName> void store(foodName * object){
(*getBasket<foodName>()).push_back(object);
};
template<typename foodName> int countSize(){
return (*getBasket<foodName>()).size();
};
private:
std::vector<Apple*> applebasket_;
std::vector<Potato*> potatobasket_;
template <typename foodName> std::vector<foodName*> * getBasket(){
std::vector<foodName*> * result;
switch(foodName::typeID){
case 0:
result = &applebasket_;
break;
case 1:
//result = &potatobasket_;
break;
}
return result;
}
};
存储.cpp
#include "Storage.h"
int Apple::typeID;
int Potato::typeID;
Storage::Storage() {
Apple::typeID = 0;
Potato::typeID =1;
}
主文件
#include "Storage.h"
#include <iostream>
int main() {
Apple* apple;
Potato* potato;
Storage storage;
int i;
for(i = 0;i < 7;i++){
apple = new Apple(i);
storage.store<Apple>(apple);
}
std::cout<<storage.countSize<Apple>();
return 0;
}
此代码工作并输出正确大小的向量,但如果未注释 switch 语句(在 Storage.h 内)中的 case 行,编译器(g++)会抛出“错误:无法将 'std::vector < Potato*>* ' 转换为 'std ::vector< Apple*>* ' 在赋值中”。无论如何,这就像编译器尝试两种情况一样,我找不到它是否可能以及如何避免这种情况。我需要这方面的帮助,也许需要一些关于整个事情的建议(不同类型容器的一个接口),我最近开始学习 C++,可能我在这里尝试这样做的方式完全是一团糟。