Apple.h
class Apple {
public:
Apple(int);
static int typeID;
private:
int id_;
};
Apple.cpp
#include "Apple.h"
Apple::Apple(int pID) {
id_ = pID;
}
Potato.h, Potato.cpp identical to Apple
Storage.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:
break;
}
return result;
}
};
Storage.cpp
#include "Storage.h"
int Apple::typeID;
int Potato::typeID;
Storage::Storage() {
Apple::typeID = 0;
Potato::typeID =1;
}
main.cpp
#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;
}
This code works and prints the right size of the vector, but if the case line in the switch statement (inside Storage.h) is uncommented, the compiler (g ++) throws "error: cannot convert 'std :: vector <Potato *> *' to 'std :: vector <Apple *> * 'on assignment. " It looks like the compiler checks both cases anyway, and I cannot find it, and how to avoid it. I need help with this and maybe some advice on the whole subject (one interface for containers of different types), I started learning C ++ recently, and probably the way I'm trying to do this is a complete mess.