user2269707
user2269707

Reputation:

cross forward declarations in template classes/functions

I get two heads: header1:

#ifndef CPPSH_A_H
#define CPPSH_A_H
class B;
class A {
 public:
  template<typename T>
  void Function1() {
    b_->Function2<int>();
  }
  template<typename T>
  void Function2() {

  }
 private:
  B* b_;
};
#endif //CPPSH_A_H

and header2:

#ifndef CPPSH_B_H
#define CPPSH_B_H
class A;
class B {
 public:
  template<typename T>
  void Function1() {
    a_->Function2<int>();
  }
  template<typename T>
  void Function2() {

  }
 private:
  A* a_;
};
#endif //CPPSH_B_H

and you can see that both a_ and b_ is incomplete type, and the calls on it is invaild. if these two classes are normal classes, I can move the Test() implementation to source file, and then include the proper header.

But since template classes/functions must define and declare their implementation in headers, how to deal this problem?

Upvotes: 2

Views: 26

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

You can merge the two headers into one, e.g.

// forward declaration
class B; 
class A {
 public:
  // member function template declaration
  template<typename T>
  void Function1();
  template<typename T>
  void Function2() {
  }
 private:
  B* b_;
};

class B {
 public:
  template<typename T>
  void Function1() {
    a_->Function2<T>();
  }
  template<typename T>
  void Function2() {
  }
 private:
  A* a_;
};

// member function template definition
template<typename T>
void A::Function1() {
  b_->Function2<T>();
}

Upvotes: 1

Related Questions