C++模板编译要编译两次。
以函数模板为例:
第一次编译检查语法
第二次编译生成具体的模板函数
第一次编译发生在正常的编译期间,第二次编译发生在函数模板调用期间。
C++编译机制C++多文件是独立编译,互不干扰的。
两种编译方式的冲突
main.cpp
#include "Person.cpp"
int main()
{
Person a(20, 123);
a.Print();
return 0;
}
Person.cpp
#include "Person.h" #includeusing namespace std; template void Person ::Print() { cout << this->mAge << " " << this->mId << endl; }
Person.h
#pragma once templateclass Person { public: T mId; T mAge; public: Person(T mId, T mAge) :mId(mId), mAge(mAge) {} void Print(); };
是因为模板只经过一次编译,导致第二次编译无法进行,从而报错找不到函数定义。
main文件包含Person.cpp,而不是Person.h
但是这在惯用法上区别工程,可以将Person.cpp文件改为Person.hpp文件,并包含Person.hpp文件,表明这是一个头文件和源文件一起的文件。



