Backto C/C++ Index
// definition
template<class T>
T GetMax(const T& a, const T& b){
return (a > b? a:b);
}
// usage
int main() {
int i = 5, j=6;
float m = 1.3, n = 3.14;
int k = GetMax<int>(i, j);
float l = GetMax<float>(m,n);
...
}
Details
D01:声明和实现必须在一起让编译器看到
就像 inline
关键字一样. 但是为了隔离 declaration
和 definitions
, 有各种方式.
- 放在单独的template 文件里, 不隔离.
- template function 就写在
.h
文件里, 不隔离 - template class 隔离, 但是指明模板 T 的可能性
// .h template<typename T> class foo { public: void bar(const T &t); }; //.cpp template <class T> void foo<T>::bar(const T &t) { } // Explicit template instantiation template class foo<int>;
Ref
- C++ Templates: 总结的很完备了
- Storing C++ template function definitions in a .CPP file: 文件隔离的各种可能性