Search code examples
c++templatestypedefmixins

base class using a type defined by the parent class


I have a Visual Studio 2008 C++ application where a base class A_Base needs to instantiate a data member whose type is defined by a parent class. For example:

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;
}

Unfortunately, it appears the compiler doesn't know what T::Foo is until it's too late and I get errors like this:

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

Is there any way to achieve this type of functionality?

Thanks, PaulH


Solution

  • You can try the following:

    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;
    }