当前位置:网站首页>Can I compile the header file and source file of the template separately

Can I compile the header file and source file of the template separately

2022-04-23 14:05:00 JokerYourMemory

    Strictly speaking , no way , However, this problem can be solved by ingenious means .

First, why not : Cite examples from this article     Why? C++ The compiler cannot support separate compilation of templates ,

//-------------test.h----------------//
template<class T>
class A
{
  public:
  void f(); //  This is just a statement 
};

//---------------test.cpp-------------//
#include”test.h”
template<class T>
void A<T>::f()  //  Template implementation 
{
  …//do something
}
 
//---------------main.cpp---------------//
#include”test.h”
int main()
{
  A<int> a;
  f(); // #1
}

To put it bluntly It's a function template 、 Class template , Instantiate as a function definition at compile time ( Whether it can be instantiated depends on whether the compiler can make the template instance come out The sentence of ). The cross file function call is in link I'll find it when I need it After instantiation Function of . Because the header file is only used as a place to declare template classes or functions . Corresponding CPP Just as an implementation place , Then its instantiation will not be triggered , That's it CPP Corresponding .OBJ There is no specific function information in the file . This is a problem .


Then how to solve it ?

Two ways of thinking , I didn't think of anything else for the time being

  The first is to let the template know main How the function calls his , Then you need to put the definition of the template in the header file , then main Functional cpp Just include it in the header file . But if there are multiple classes 、 It's all done in this way , Then the problem of repeated definitions will occur during compilation , Similar to my last article Can global variables be declared in the header file .

  Another idea is , Give Way .h share .cpp Information about , That is to say .h add #include<.cpp>, But this kind of .h contain .cpp Is your approach rigorous .

There's another way , Since the link is not possible, it is because there is no call to generate class instances during compilation , So can you call this class or function through an independent function To generate one . It's fine too , But it still faces the risk of repeated definition of the first approach .





版权声明
本文为[JokerYourMemory]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231401091135.html