代码之家  ›  专栏  ›  技术社区  ›  Walter

模板的选择性编译

  •  0
  • Walter  · 技术社区  · 6 年前

    // file.h
    template<typename T> class object { /* lots of code */ };
    
    // file.inc
    template<typename T>
    object::object(const T*data) { /* ... */ }
        // and more: definitions of all non-inline functionality of class object<>
    
    // file.cc to be compiled and linked
    #include "file.h"
    #include "file.inc" 
    
    template struct<int>;
    template struct<double>;
    
    // user.cc
    #include "user.h"
    #include "file.h"
    
    object<double> x{0.4}                              // okay: uses pre-compiled code
    object<user_defined> z(user_defined{"file.dat"});  // error: fails at linking
    

    如果用户 #include s码 "file.inc"

    // user.cc
    #include "user.h"
    #include "file.h"
    #include "file.inc"
    
    object<double>  x{0.4}                            // error: duplicate code 
    object<user_defined> z(user_defined{"file.dat"}); // okay
    

    file.cc .

    1 回复  |  直到 6 年前
        1
  •  1
  •   Vittorio Romeo    6 年前

    你可以用 extern template 防止在给定的TU中实例化模板。

    // src0.cpp
    
    template class foo<int>;
        // Oblige instantiation of `foo<int>` in this TU
    

    // src1.cpp
    
    extern template class foo<int>;
        // Prevent instantiation of `foo<int>` in this TU
    

    src0 src1 连接在一起,你的程序就可以运行了。