函数模板

参考:Function Templates

函数模板定义示例如下:

template< class T > 
void MySwap( T& a, T& b ) {
   T c(a);
   a = b;
   b = c;
}

实例化示例如下:

// function_template_instantiation.cpp
template<class T> void f(T) { }

// Instantiate f with the explicitly specified template.
// argument 'int'
//
template void f<int> (int);

// Instantiate f with the deduced template argument 'char'.
template void f(char);
int main()
{
}

显式实例化

参考:Explicit Instantiation

在创建使用模板进行分发的库(.lib)文件时,未实例化的模板定义不会放入对象(.obj)文件中

# 显式实例化模板MyStack
template class MyStack<int, 6>;

可使用关键字extern阻止模板的实例化

extern template class MyStack<int, 6>;

模板专门化中的extern关键字仅适用于在类主体外部定义的成员函数。类声明中定义的函数被视为内联函数,总是被实例化

函数模板的偏序

参考:Partial Ordering of Function Templates (C++)

成员函数模板

成员模板指的是成员函数模板和嵌套类模板

成员函数模板指的是类或类模板的成员的函数模板

struct X
{
   template <class T> void mf(T* t) {}
};

template<typename T>
class X
{
public:
   template<typename U>
   void mf(const U &u)
   {
   }
};

template<typename T>
class X
{
public:
   template<typename U>
   void mf(const U &u);
};

template<typename T> template <typename U>
void X<T>::mf(const U &u)
{
}