Base class using the type defined by the parent class

I have a Visual Studio 2008 C ++ application where a base class A_Baseneeds to create an instance of a data item whose type is determined by the parent class. For instance:

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 seems that the compiler does not know that T::Foountil it is 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 a way to achieve this type of functionality?

Thanks PaulH

+3
source share
3 answers

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;
}
+3
source

A_Base<A>created at the point where Ait is not yet complete:

class A : public A_Base< A >

You can use the feature class:

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

The class Adepends on the class A_Base, which depends on the class A... etc. There is recursion here. You must declare Fooin a separate class.

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

See also GotW # 79 .

+1
source

Source: https://habr.com/ru/post/1778801/


All Articles