使用父类定义的类型的基类

Pau*_*ulH 3 c++ templates typedef mixins

我有一个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;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,似乎编译器不知道是什么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
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这种功能?

谢谢,PaulH

ice*_*ime 5

A_Base<A>A尚未完成的位置实例化:

class A : public A_Base< A >
Run Code Online (Sandbox Code Playgroud)

你可以考虑使用traits类:

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;
}
Run Code Online (Sandbox Code Playgroud)