例子:
说我在预编译的头文件中包括:

#include <vector>

由于在我的项目中经常使用vector的一些实例,例如std::vector,std::vector等,因此,如果我也在预编译 header 中实例化它们,也会减少编译时间:
#include <vector>
template class std::vector<float>;
template class std::vector<int>;

更进一步,将伪函数添加到使用一些函数的预编译头中是否有意义:
namespace pch_detail {
inline auto func() {
  auto&& v = std::vector<float>{};
  v.size();
  v.begin();
  v.front();
}
}

我不确定翻译单元和模板如何真正工作,因此在我看来,如果我在预编译的 header 中实例化它们,这意味着不必为每个.cpp文件都实例化它们。

更新

使用Visual Studio 2017和一些常用模板类的实例化在真实世界的代码库上进行了测试。
  • 带有实例化的通用模板类:71731 ms
  • 不带实例:68544 ms

  • 因此,至少就我而言,这花费了更多时间。

    最佳答案

    有趣的是,但至少对于clang(4.0.1),您的变量会增加编译时间:

    1. no pch
    
    real    0m0,361s
    user    0m0,340s
    sys     0m0,021s
    
    2. pch, no explicit instantiate
    
    real    0m0,297s
    user    0m0,280s
    sys     0m0,017s
    
    3. pch, explicit instantiate
    
    real    0m0,507s
    user    0m0,474s
    sys     0m0,033s
    

    我使用这样的代码:
    #include <iostream>
    #include "test.h"
    
    int main() {
            std::vector<float> a = {1., 2., 3.};
            for (auto &&e : a) {
                    std::cout << e << "\n";
            }
            std::vector<int> b = {1, 2, 3};
            for (auto &&e : b) {
                    std::cout << e << "\n";
            }
    }
    

    案例2 test.h
    #pragma once
    
    #include <vector>
    

    情况3
    #pragma once
    
    #include <vector>
    template class std::vector<float>;
    template class std::vector<int>;
    

    以及这样的编译脚本:
    echo "no pch"
    time clang++ -std=c++11 main.cpp
    
    echo "pch, no explicit instantiate"
    clang++ -std=c++11 -x c++-header test.h -o test.pch
    time clang++ -std=c++11 -include-pch  test.pch main.cpp
    
    echo "pch, explicit instantiate"
    clang++ -std=c++11 -x c++-header test2.h -o test2.pch
    time clang++ -std=c++11 -include-pch  test2.pch main2.cpp
    

    10-08 08:54
    查看更多