Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template inheritance error in c++

I have two header files A.h(include a pure virtual function) and B.h.

A.h :

#ifndef __A_H__
#define __A_H__

#include "B.h"
template <class T>
class A
{
   virtual B<T> f()=0;
};

#endif

B.h :

#ifndef __B_H__
#define __B_H__

#include "A.h"
template <class T>
class B : public A <T> 
{
  B<T> f(){}
};

#endif

but when I compile it gives me error like that
In file included from B.h:4,
from Test.cpp:1:
A.h:10: error: ISO C++ forbids declaration of ‘B’ with no type
A.h:10: error: ‘B’ declared as a ‘virtual’ field
A.h:10: error: expected ‘;’ before ‘<’ token

#include "B.h"

int main() {
 return 0;
}

how can I solve this ? thanks


1 Answers

The only way is with forward declare :

#ifndef __A_H__
#define __A_H__

template< typename > class B;

template <class T>
class A
{
   virtual B<T>* f()=0;
};

#endif

You have a problem with circular dependency which can be solved only using forward declare.

like image 105
BЈовић Avatar answered Apr 04 '26 06:04

BЈовић



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!