Consider a file main.cc with the following code:
template<typename Commodity>
class Shop
{
public:
Shop(){}
~Shop(){}
};
template<typename FuelType>
class Car
{
public:
Car(){}
virtual ~Car(){}
};
template<typename FuelType>
class Volkswagen : public Car<FuelType>
{
public:
Volkswagen(){}
~Volkswagen(){}
};
int main()
{
// this is fine...
Car<int>* myCar = new Volkswagen<int>();
delete myCar;
// ...but this isn't
Shop<Car<int>>* myCarShop = new Shop<Volkswagen<int>>();
return 0;
}
When I try to compile, I get an error:
cannot convert 'Shop<Volkswagen<int> >*' to 'Shop<Car<int> >*' in initialization...'
Now, I understand why I get this error. It's because Shop<Volkswagen<T>>
in general does not have to inherit from Shop<Car<T>>
.
My question is: How can I implement a structure like this? Is there a better way with classes and templates or should I, when I'm absolutely certain that Shop<Volkswagen<T>>
always is a Shop<Car<T>>
, attempt to explitly cast the pointer?
Edit 1: One solution could be to add a class
template<typename FuelType>
class VolkswagenShop : public Shop<Volkswagen<FuelType>>, public virtual Shop<Car<FuelType>>
{
public:
VolkswagenShop(){}
~VolkswagenShop(){}
};
and then write
Shop<Car<int>>* myCarShop = new VolkswagenShop<int>();
This compiles, but the structure has gotten complicated to a point where I, with my very limited c++ ability, am not sure if this won't cause any problems.
So, risking being too vague, will the above solution cause any obvious problems?
Aucun commentaire:
Enregistrer un commentaire