File ex1.hpp (definition of template class):
#ifndef EX1_HPP
#define EX1_HPP
#include "ex2.hpp"
template <class T>
class Ex1{
public:
void Ex1method(){
Ex2 a; // using nontemplate class object
a.Ex2method();
}
};
#endif
File ex2.hpp (definition of nontemplate class):
#ifndef EX2_HPP
#define EX2_HPP
#include "ex1.hpp"
class Ex2{
public:
void Ex2method();
};
#endif
File ex2.cpp (definition of nontemplate class method):
#include "ex2.hpp"
void Ex2::Ex2method()
{
Ex1<int> e; // using template class object
e.Ex1method();
}
Compilation error:
ex1.hpp:10:9: error: ‘Ex2’ was not declared in this scope
ex1.hpp:10:13: error: expected ‘;’ before ‘a’
ex1.hpp:11:9: error: ‘a’ was not declared in this scope
How can be such circular dependency between nontemplate class and template class resolved? I cannot be definition of nontemplate class methods to implementation file, because it will cause linker error. If I place forward declaration of Ex2 class in file ex1.hpp, then error is:
error: invalid use of incomplete type ‘struct Ex2’
error: forward declaration of ‘struct Ex2’
Don’t include
ex1.hppinex2.hpp, it is not necessary there. You don’t have a circular dependency with your headers.Include both headers (or just
ex1.hpp) in your.cppfile and all should be good.