2010-12-06 20 views
3

基底クラスA_Baseが親クラスによって型が定義されているデータメンバーをインスタンス化する必要があるVisual Studio 2008 C++アプリケーションがあります。たとえば:親クラスで定義された型を使用している基底クラス

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

あなたは次のことを試すことができます:あなたが使用して検討することもでき

class A : public A_Base<A> 

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がまだ完了していない時点でインスタンス化されます形質クラス:

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 ...などに依存するクラスA_Baseに依存します。ここでは再帰があります。別のクラスにFooと宣言する必要があります。

class A; 

template<typename T> struct Foo; 
template<> struct Foo<A> { typedef int type; }; 

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

private: 
    Bar bar_; 
}; 

class A : public A_Base<A> 
{ 
}; 

GotW #79も参照してください。

関連する問題