2012-09-06 74 views
0

Possible Duplicate:
Where and why do I have to put the 「template」 and 「typename」 keywords?的typedef爲模板內模板

我有創建一個對象,並傳遞所期望的類作爲模板參數時,創建一個智能指針的類。而且我有另一個類需要在另一個類中使用該智能指針。

#include <iostream> 
using namespace std; 

//智能指針類

template<typename T> 
class IntrusivePtr 
{ 
public: 
    IntrusivePtr() 
    { 
     cout << "IntrusivePtr()"; 
    } 
}; 

//類,我需要一個智能指針,這也是模板

template<typename T> 
class A 
{ 
public: 
    A() 
    { 
     cout << "A()"; 
    } 
    typedef IntrusivePtr< A<T> > my_ptr; 
}; 

使用智能指針//類。

template<typename T> 
class B 
{ 
public: 
    B() 
    { 
     cout << "B()"; 
    } 

    typedef A<T>::my_ptr x; 
}; 



int main() 
{ 
    B<int> ob; 

    return 0; 
} 

這可以在C++中實現嗎? 我知道新的C++ 11支持typedef S表示這樣的事情,但我使用的舊標準:( 編譯這個我得到一些不好的屁股錯誤:

C:\Users\iuliuh\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: error: C2146: syntax error : missing ';' before identifier 'x'

C:\Users\iuliuh\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: error: C2146: syntax error : missing ';' before identifier 'x'

C:\Users\iuliuh\typedef_template_class-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2008__Qt_SDK__Debug..\typedef_template_class\main.cpp:41: error: C4430: missing type specifier - int assumed. Note: C++ does not support default-int

編輯: 對不起,我改變了一些東西,錯誤代碼。這是我希望它是。對不起

回答

3
template<typename T> 
class B 
{ 
public: 
    B() 
    { 
     cout << "B()"; 
    } 

    typedef typename A<B>::my_ptr x; 
}; 

你應該使用typename,因爲my_prtdependent name

+0

工作,謝謝:) –

+0

要了解更多有關從屬名稱,請查看此[excelent SO回答!](http://stackoverflow.com/a/613132/499359):)對我來說這是非常有用的。 –

+0

@PaperBirdMaster謝謝。值得一讀 –

3

您的問題是A<B>::my_ptr是依賴名稱(取決於B<T>,因此取決於模板參數T)。出於這個原因,編譯器在解析模板時不知道它是否應該是類型或變量。在這種情況下,它假設my_ptr不是一種類型,除非你非常明確地告訴它。因此,你需要添加typename,就像編譯器告訴你這樣做:

typedef typename A<B>::my_ptr x; 

更完整的解釋look at this answer to a similar question

+0

感謝您的回覆和鏈接。我現在開始閱讀! –