How to declare/define interdependent templates in C++?

前端 未结 2 659
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 05:02

Usually in C++ when I need interdependencies between classes, I use forward declarations in the header files and then include both header files in each cpp file.

How

2条回答
  •  佛祖请我去吃肉
    2020-12-20 05:29

    You can separate the declarations and definitions of classes. Therefore you can separate the declarations and definitions of template classes...

    You can separate the declarations and definitions of class methods. Therefore you can separate the declarations and definitions of template class methods:

    template struct B;     // declaration
    
    template struct A {     // definition
      void RunA(B *pB);  // declaration
    };
    
    template struct B {     // definition
      void RunB(A *pA);   // declaration
    };
    
    // definition
    template
    void A::RunA(B *pB) {
        // need to do something to B here
      }
    
    // definition    
    template
    void B::RunB(A *pA) {
        // need to do something to A here
      }
    

提交回复
热议问题