如何将A <B <T >> *解释为A <C <T >> *,其中B:公共C <T>?

考虑带有以下代码的文件main.cc:

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;
}

当我尝试编译时,出现错误:

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?

评论