我也一直在想这个办法,我心里也有这个问题。(但我是菜鸟...)
另一个参考:https ://msdn.microsoft.com/en-us/library/by56e477.aspx
也许extern
需要明确的?
但是,到链接的时候,cpp文件已经编译成了.obj
's,但.pch
不是.obj
……那么,模板函数的实例化在哪里呢?链接器是否能够从.pch
?
或者我们需要另一个单独.cpp
的专用于实例化它们,同时将所有客户端引用声明为extern
?
并且.. 链接时间代码生成?
有一些尝试
它有点作用。使用 VS2012 进行测试。打开编译器分析并观察编译器输出。
// stdafx.h
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>
#include <vector>
#include <set>
#include <deque>
// stdafx.cpp
#include "stdafx.h"
using namespace std;
template class set<int>;
template set<int>::set();
template set<int>::_Pairib set<int>::insert(const int&);
template class deque<int>;
template deque<int>::deque();
template void deque<int>::push_back(const int&);
template class vector<int>;
template vector<int>::vector();
template void vector<int>::push_back(const int&);
// playcpp.cpp, the entry point
#include "stdafx.h"
using namespace std;
// toggle this block of code
// change a space in the "printf", then build (incrementally)
/*
extern template class set<int>;
extern template set<int>::set();
extern template set<int>::_Pairib set<int>::insert(const int&);
extern template class deque<int>;
extern template deque<int>::deque();
extern template void deque<int>::push_back(const int&);
extern template class vector<int>;
extern template vector<int>::vector();
extern template void vector<int>::push_back(const int&);
*/
int _tmain(int argc, _TCHAR* argv[])
{
set<int> s;
deque<int> q;
vector<int> v;
for(int i=0;i<10000;i++){
int choice=rand()%3;
int value=rand()%100;
switch(choice){
case 0: s.insert(value); break;
case 1: q.push_back(value); break;
case 2: v.push_back(value); break;
}
}
for(const auto &i:s)
printf("%d",i);
for(const auto &i:q)
printf("%d ",i);
for(const auto &i:v)
printf("%d ",i);
return 0;
}
结果(很多其他的省略了)
带有外部声明:
1> 1630 毫秒 Build 1 次调用
...
1> 757 毫秒 ClCompile 1 次调用
1> 787 毫秒 Link 1 次调用
没有外部声明:
1> 1801 毫秒 Build 1 次调用
...
1> 774 毫秒 Link 1 次调用
1> 955 毫秒 ClCompile 1 次调用
(中文版。图例:毫秒:毫秒/毫秒,x 次调用:x 调用/被调用 x 次)
调整电源设置以让 CPU 运行缓慢,以获得更长的时间来避免湍流。
以上只是每种情况的一个样本。尽管如此,它还是很不稳定。这两种情况有时可能会多运行约 200 毫秒。
但是尝试了很多次,平均总是有大约 200ms 的差异。我只能说平均值在 1650 毫秒和 1850 毫秒左右,ClCompile 的时间完全不同。
当然还有更多对其他模板成员函数的调用,只是我没有时间弄清楚所有这些类型签名......(谁能告诉我它将使用哪个(const)迭代器?)
好吧,但是……有更好的方法吗?