c++ template(5)模板实战
生活随笔
收集整理的這篇文章主要介紹了
c++ template(5)模板实战
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一.包含模型
一份頭文件hpp,一份cpp實現文件
hpp:
#ifndef MYFIRST_HPP #define MYFIRST_HPP// declaration of template template <typename T> void print_typeof (T const&);#endif // MYFIRST_HPPcpp:
#include <iostream> #include <typeinfo> #include "myfirst.hpp"// implementation/definition of template template <typename T> void print_typeof (T const& x) {std::cout << typeid(x).name() << std::endl; }使用模板函數:
#include "myfirst.hpp" // use of the template int main() {double ice = 3.0;print_typeof(ice); // call function template for type double }將會導致鏈接錯誤,必須有一個基于double實例化的函數定義
為了通過編譯,有2兩種辦法:
1.把cpp文件包含在頭文件里面
2.在使用模板的文件中引用cpp文件
3.不要cpp文件,將聲明和實現都放在hpp文件里面
#define MYFIRST_HPP#include <iostream> #include <typeinfo>// declaration of template template <typename T> void print_typeof (T const&);// implementation/definition of template template <typename T> void print_typeof (T const& x) {std::cout << typeid(x).name() << std::endl; }#endif // MYFIRST_HPP開銷:
1.增加了頭文件的大小
2.增加了編譯復雜度
二.手工顯式實例化
聲明一個顯式實例化的頭文件
#include "myfirst.hpp"// explicitly instantiate print_typeof() for type double template void print_typeof<double>(double const&);現在使用這個頭文件,編譯正常
#include "myfirstinst.cpp" // use of the template int main() {double ice = 3.0;print_typeof(ice); // call function template for type double }優點:避免了龐大的頭文件開銷
注意點:一個程序中最多只有一個顯式實例化體
三.整合包含模型和顯式實例化
如上聲明3份文件.
如下2種用法:
第一種使用應該引用“stackdef.hpp”
總結
以上是生活随笔為你收集整理的c++ template(5)模板实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++ template(10)类型函数
- 下一篇: c++ template(4)基本技巧