您的代码无法编译,因为两者case
应该编译这是不可能的,因为两者的类型不同case
.
解决这个问题的一种方法是使用重载而不是函数模板 as (这意味着,不需要typeID
在你的班级!):
std::vector<Apple*> * get_basket(Apple *)
{
return &applebasket_; //return pointer to the apple basket
}
std::vector<Potato*> * get_basket(Potato *)
{
return &potatobasket_; //return pointer to the potate basket
}
并将其称为:
template<typename FoodType>
void store(FoodType * object)
{
std::vector<FoodType> * basket = get_basket(static_cast<FoodType*>(0));
basket->push_back(object);
}
这里的技巧是你有两个重载,每个重载都有一个参数不同的类型,所以你使用static_cast<FoodType*>(0)
帮助编译器根据以下内容选择正确的重载type表达式的static_cast<FoodType*>(0)
这将是任一类型Apple*
or Potato*
.
@Gorpik 评论里说 https://stackoverflow.com/a/11035109/415784两者(这个以及其他解决方案)都很丑陋,所以这是解决这个问题的另一种尝试。
定义一个base_storage
类模板为:
template<typename FoodType>
class base_storage
{
std::vector<FoodType*> m_storage;
public:
void store(FoodType *foodItem)
{
m_storage.push_back(foodItem);
}
size_t count() const
{
return m_storage.size();
}
};
该基类存储以下食品one仅键入,但在问题中,我们需要存储以下食品two类型。因此,为了做到这一点,我们定义另一个类Storage
从上面的类模板派生为:
class storage : private base_storage<Apple>, private base_storage<Potato>
{
public:
template<typename FoodType>
void store(FoodType * foodItem)
{
base_storage<FoodType>::store(foodItem);
}
template<typename FoodType>
size_t count() const
{
return base_storage<FoodType>::count();
}
};
这里要注意两点:
- 班上
storage
现在没有任何会员数据。它只是将调用转发到根据模板参数的类型选择的基类FoodType
.
- 由此衍生出私下里来自基类。所以它不是
is-a
关系。
请在此处查看该解决方案的在线演示:http://ideone.com/Ykjo5 http://ideone.com/Ykjo5
这个解决方案的优点在于,如果你想让它工作three食物类型,那么你需要从中获取它three基类为:
class storage : private base_storage<Apple>,
private base_storage<Potato>,
private base_storage<Mango> //added line!
{
//same as before; no change at all !
};
Demo : http://ideone.com/lnMds http://ideone.com/lnMds