Home > Mobile >  Using type in template class of derived template class
Using type in template class of derived template class

Time:12-15

Try to implement the CRTP pattern. Therefore I created two template classes. With the first draft of only one template class PDerived everything is fine. But for my purpose in a bigger project I need two template classes. Which results in an error: All types of the PDerivced class are not found. But I have no idear why. In the following the is a minimalistic example.

In this example myType can not be found? If TDerived is no template class everything is fine. Is there some namespace needed?

#include <iostream>

template< typename PDerived >
class TBase
{
 public:
  using myType = uint8_t;

  void Foo( void )
  {
   static_cast< PDerived* > ( this )->Bar();
  }
};

template< typename Derived > class TDerived : public TBase< TDerived<Derived> >
{
  friend class TBase< TDerived > ;
 protected:
  void Bar( void )
  {
   std::cout << "in Bar" << std::endl;
  }
 private:
  myType myVariable;

};

int main( void )
{
 TDerived<uint8_t> lD;

 lD.Foo();

 return ( 0 );
}

Error message:

error: 'myType' does not name a type

CodePudding user response:

If you want to refer to some templated stuff of your base class, you have to give the compiler a hint how to find it.

Change your line:

myType myVariable;

to

TBase< TDerived<Derived> >::myType myVariable;

The underlying problem is, that unqualified names are not resolved during this stage until the template is fully defined. You get the same problem if you try to call member functions or variables from your base class. In this case you can simply use this->MemberFunc().

  •  Tags:  
  • c
  • Related