2017-04-02 23 views
1

返回此我已使用該:C++ shared_ptr的衍生自方法

struct Bar; 

struct Foo 
{ 
    virtual Bar * GetBar() { return nullptr; } 
} 

struct Bar : public Foo 
{ 
    virtual Bar * GetBar() { return this; } 
} 

Foo * b = new Bar(); 
//... 
b->GetBar(); 

我用來代替慢dynamic_cast此。現在,我已經改變了我的代碼使用std::shared_ptr

std::shared_ptr<Foo> b = std::shared_ptr<Bar>(new Bar()); 

我怎樣才能改變GetBar方法返回std::shared_ptr並獲得相同的功能與原始指針(無需dynamic_cast的)?

我已經試過這樣:

struct Foo : public std::enable_shared_from_this<Foo> 
{ 
    virtual std::shared_ptr<Bar> GetBar() { return nullptr; } 
} 


struct Bar : public Foo 
{ 
    virtual std::shared_ptr<Bar> GetBar() { return shared_from_this(); } 
} 

,但它不會編譯

+1

當然'GetBar'不應該返回'酒吧*' - 但'美孚*' –

+0

@EdHeal這會破壞目的。 –

回答

5

std::enable_shared_from_this<Foo>::shared_from_this()返回shared_ptr<Foo>。所以你需要一個明確的指針向下。

virtual std::shared_ptr<Bar> GetBar() { 
    return std::static_pointer_cast<Bar>(shared_from_this()); 
}