2010-12-06 39 views
3

我有一個Visual Studio 2008 C++應用程序,其中基類A_Base需要實例化其類型由父類定義的數據成員。例如:使用由父類定義的類型的基類

template< typename T > 
class A_Base 
{ 
public: 
    typedef typename T::Foo Bar; // line 10 

private: 
    Bar bar_; 
}; 

class A : public A_Base<A> 
{ 
public: 
    typedef int Foo; 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    A a; 
return 0; 
} 

不幸的是,它出現在編譯器不知道T::Foo是什麼,直到爲時已晚,我得到象這樣的錯誤:

1>MyApp.cpp(10) : error C2039: 'Foo' : is not a member of 'A' 
1>  MyApp.cpp(13) : see declaration of 'A' 
1>  MyApp.cpp(14) : see reference to class template instantiation 'A_Base<T>' being compiled 
1>  with 
1>  [ 
1>   T=A 
1>  ] 
1>MyApp.cpp(10) : error C2146: syntax error : missing ';' before identifier 'Bar' 
1>MyApp.cpp(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
1>MyApp.cpp(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 

有什麼辦法來實現這種類型的功能?

感謝, PaulH

回答

3

你可以嘗試以下方法:

template< typename T > 
class A_Base 
{ 
public: 
    typedef typename T::Foo Bar; // line 10 

private: 
    Bar bar_; 
}; 

class A_Policy 
{ 
public: 
    typedef int Foo; 
}; 

class A : public A_Base<A_Policy> 
{}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    A a; 
return 0; 
} 
5

A_Base<A>在一個點上被實例化,其中A尚未完成:

class A : public A_Base<A> 

你可以考慮使用性狀等級:

template<class T> struct traits; 

template< typename T > 
class A_Base 
{ 
public: 
    typedef typename traits<T>::Foo Bar; // line 10 

private: 
    Bar bar_; 
}; 

class A; // Forward declare A 

template<> // Specialize traits class for A 
struct traits<A> 
{ 
    typedef int Foo; 
}; 

class A : public A_Base<A> {}; 

int main() 
{ 
    A a; 
} 
1

A取決於類A_Base這取決於類A等等。您在這裏有一個遞歸。您需要在單獨的課程中聲明Foo。參考GotW #79