我有这样的事情:
enum EFood{
    eMeat,
    eFruit
};

class Food{
};

class Meat: public Food{
    void someMeatFunction();
};

class Fruit: public Food{
    void someFruitFunction();
};

class FoodFactory{
    vector allTheFood;
    Food* createFood(EFood foodType){
        Food* food=NULL;
        switch(foodType){
            case eMeat:
                food = new Meat();
                break;
            case eFruit:
                food = new Fruit();
                break;
        }
        if(food)
            allTheFood.push_back(food);
        return food;
    }
};

int foo(){
    Fruit* fruit = dynamic_cast(myFoodFactory->createFood(eFruit));
    if(fruit)
        fruit->someFruitFunction();
}
现在我想更改我的应用程序以使用boost shared_ptr和weak_ptr,以便我可以在一个地方删除我的食物实例。它看起来像这样:
class FoodFactory{
    vector > allTheFood;
    weak_ptr createFood(EFood foodType){
        Food* food=NULL;
        switch(foodType){
            case eMeat:
                food = new Meat();
                break;
            case eFruit:
                food = new Fruit();
                break;
        }

        shared_ptr ptr(food);
        allTheFood.push_back(ptr);
        return weak_ptr(ptr);
    }
};

int foo(){
    weak_ptr fruit = dynamic_cast >(myFoodFactory->createFood(eFruit));
    if(shared_ptr fruitPtr = fruit.lock())
        fruitPtr->someFruitFunction();
}
但问题是dynamic_cast似乎不适用于weak_ptr 如果我知道它指向的对象是派生类型的话,我如何从
weak_ptr
中得到一个
weak_ptr
?