2014-01-29 114 views
1

我試圖從它的模板容器類返回一個嵌套的模板對象C++嵌套模板的返回類型

template <typename T> 
class A { 
    template <typename S> 
    struct node { 
     S value; 
     struct node<S>* right; 
     .... 
    }; 
    private: 
     .... 
     node<T>* foo(); 
} 

我遇到那麼

template <typename T> 
A<T>::node<T>* A<T>::foo() { 
.... 
} 

這是Visual Studio的錯誤

1> A.cpp 
1>c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.cpp(576): warning C4346: 'A<T>::[email protected][email protected]@' : dependent name is not a type 
1>   prefix with 'typename' to indicate a type 
1>c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.cpp(576): error C2143: syntax error : missing ';' before '*' 
1>c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.cpp(576): error C2065: 'T' : undeclared identifier 
1>c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.cpp(576): error C2923: 'A' : 'T' is not a valid template type argument for parameter 'T' 
1>c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.cpp(576): error C2923: 'A<T>::node' : 'T' is not a valid template type argument for parameter 'S' 
1>c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.cpp(613): error C2509: 'foo' : member function not declared in 'A' 
1>   c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.h(11) : see declaration of 'A' 
1>c:\users\user\dropbox\visual studio projects\fooProj\fooProj\A.cpp(613): fatal error C1903: unable to recover from previous error(s); stopping compilation 

我錯過了太明顯的東西?

編輯:

A.h
#ifndef TEMP_H 

#define TEMP_H 

template <typename T> 
class A { 
    template <typename S> 
    struct node 
    { 
     S value; 
     struct node* right; 
     struct node* left; 
    }; 


private: 
    node<T>* removeWithTwoChildren(); 
}; 

template <typename T> 
A<T>::template node<T>* A<T>::removeWithTwoChildren() { 
    A<T> temp = new A<T>; 
    return temp; 
} 

#endif 

它並不需要是一個結構,我還可以使用一個類。

我使用時遇到的問題VC++ 2013

的位置是在返回類型聲明

A<T>::template node<T>* 

我想回到

node<T>* 
+0

@billz但'foo'不是嵌套模板。 – Angew

+0

Try'template A :: template node * A :: foo()'(注意添加了'template',我猜是需要的,因爲'A :: node'是一個獨立的名字,編譯器需要被告知,這是一個模板,以解析以下'') – leemes

回答

4

確定。我的肢體,表明這走出去是什麼,你可能需要:

template<typename T> 
typename A<T>::template node<T>* A<T>::foo() 
{ 
    // your stuff goes here 
} 

如果你想知道在哪裏,從see this answer來了。 Johannes是C++和模板領域的絕對機器,並且坦誠地說忘記了更多關於該語言的知識比大多數人會知道的知道。閱讀該帖子。您遇到的問題來自獨立名稱解析。你需要「告訴」編譯器關注的東西也是一個模板。

+0

謝謝你的回覆,這是相同的,我是新來的模板,它在兩個文件,但如果我有聲明後#import「A. hxx「給出同樣的錯誤 – flanaras

+0

'#import' ??嗯。你的意思是'#include',對嗎? (並且模板不會進入.cpp文件,只能進入頭文件,除非非常少見的情況)。所有這些應該在*一個*標題中。發佈*真實*代碼將有助於*很多*。 – WhozCraig

+0

是#include我的意思是,我有A.h和A.hxx。已嘗試讓他們在同一個文件中,仍然是一樣的東西 – flanaras