2010-01-22 59 views
1

違規代碼:升壓:: intrusive_ptr構造歧義使用類this指針

template<typename T> 
class SharedObject { 
public: 
    typedef boost::intrusive_ptr<T> Pointer; 
    typedef boost::intrusive_ptr<T const> ConstPointer; 
    inline Pointer GetPointer() { 
    return Pointer(this); //Ambiguous call here 
    } 
    inline ConstPointer GetPointer() const { 
    return ConstPointer(this); 
    } 
    ... 

和使用這樣的:與升壓

template <typename T> 
class SomeClass: public SharedObject<SomeClass<T> > { 
public: 
    static inline boost::intrusive_ptr<SomeClass<T> > Create() { 
    return (new SomeClass)->GetPointer(); 
    } 
}; 

int main() 
{ 
    auto v = SomeClass<int>::Create(); 
} 

GCC(4.4.1)1.41給出在instatiating GetPointer()的第一個(非const)版本,此錯誤:

error: call of overloaded ‘intrusive_ptr SharedObject<SomeClass<int> >* const)’ is ambiguous 
boost/smart_ptr/intrusive_ptr.hpp:118: note: candidates are: boost::intrusive_ptr<T>::intrusive_ptr(boost::intrusive_ptr<T>&&) [with T = SomeClass<int>] <near match> 
boost/smart_ptr/intrusive_ptr.hpp:94: note:     boost::intrusive_ptr<T>::intrusive_ptr(const boost::intrusive_ptr<T>&) [with T = SomeClass<int>] <near match> 
boost/smart_ptr/intrusive_ptr.hpp:70: note:     boost::intrusive_ptr<T>::intrusive_ptr(T*, bool) [with T = SomeClass<int>] <near match> 

在C++我不到奧術技能,我看不到WH Ÿ有任何含糊之處。第188行和第94行的兩個候選值取一個現有的intrusive_ptr右值參考,其中SharedObject::this當然不是。然而,最終的候選人是一個完美的匹配(布爾參數是可選的)。

有人問我是否有問題?

編輯+回答:我終於明白了,在

inline Pointer GetPointer() { 
    return Pointer(this); //Ambiguous call here 
    } 

this指的是共享對象,而指針的typedef是SomeClass的。 (這就是巴特沃斯馬上指出的)。

inline Pointer GetPointer() { 
    return Pointer(static_cast<C*>(this)); 
    } 

因爲我知道this真的是SomeClass的,從共享對象繼承,一個的static_cast使得模板類圍棋回合。

回答

2

當你說:

typedef boost::intrusive_ptr<T> Pointer; 

您聲明型這是一種侵入式指針,int(因爲Tint在這一點),當模板在代碼中實例化。您的SharedObject類不是int,因此您無法使用this實例化此類侵入式指針。

編輯:好的,我誤解了你的代碼,我會再試一次。在:

return Pointer(this); //Ambiguous call here 

這是一個SharedObject,根據錯誤消息,但指針typedefed到一個SomeClass我認爲。

你的代碼難以置信地難以理解 - 無論你想要做什麼,都必須有一個更簡單的方法。而你似乎缺少基類中的虛擬析構函數(也可能是虛函數)。

+0

看完了。我沒有看到它。 :) – 2010-01-22 10:50:35

+0

我不知道我理解你的答案。我在原始問題中增加了一個更具體的例子。據我所見,ShareObject是通過'SomeClass '作爲T實例化的,據我瞭解,'typedef boost :: intrusive_ptr 指針'按預期工作?我不明白你的答案,還是我最初的例子太模糊了? – porgarmingduod 2010-01-22 11:06:29

+0

感謝您的幫助。它幫助我弄清楚了事情。

至於我的目標,其實並不像看起來那麼複雜。我把整個課程放在http://paste.ubuntu.com/360614/以供參考。 (我不錯過虛擬析構函數afaik)。 – porgarmingduod 2010-01-22 12:03:42