2012-12-26 38 views

回答

4

实例化时,类模板成为类,函数模板成为函数。例子:

//Defines a template for a class that can hold two 
//objects. 
template<typename T1, typename T2> 
struct pair { 
    T1 first; 
    T2 second; 
}; 

//Defines a template for a function that gives the 
//minimum of two values. 
template<typename T> 
T min(T a, T b) { 
    return a < b ? a : b; 
} 

对于普通的代码,你会当你想创建一个由类型参数化类和函数模板,当你想创建一个可以在许多不同的操作功能,使用类模板类型。

函数模板也能够做到型扣,其可以是用于创建工厂功能有用:

//Deduces the types of T1 and T2, so 
//for example, a pair<int, double> can be created 
//by `make_pair(10, 1.2)` 
template<typename T1, typename T2> 
pair<T1, T2> make_pair(T1&& t1, T2&& t2) { 
    return {std::forward<T1>(t1), std::forward<T2>(t2)}; 
} 

类模板可以用来编写执行在编译时的程序(使用类型作为值,并将模板实例与模式匹配作为纯函数)。这方面的一个简单的例子是这组类模板从而消除从类型所有const

//Removes all `const` from a type, for example: 
//`remove_const_recursive<int const*const volatile>::type` 
//is the type `int*volatile`. 
template<typename T> struct remove_const_recursive { typedef T type; }; 
template<typename T> struct remove_const_recursive<T const volatile> { 
    typedef typename remove_const_recursive<T>::type volatile type; 
}; 
template<typename T> struct remove_const_recursive<T volatile> { 
    typedef typename remove_const_recursive<T>::type volatile type; 
}; 
template<typename T> struct remove_const_recursive<T const> { 
    typedef typename remove_const_recursive<T>::type type; 
}; 
template<typename T> struct remove_const_recursive<T&> { 
    typedef typename remove_const_recursive<T>::type& type; 
}; 
template<typename T> struct remove_const_recursive<T*> { 
    typedef typename remove_const_recursive<T>::type* type; 
}; 

当你使用模板越来越多,你会发现,他们可以在各种各样的方式来使用。 Expression templates允许您加快某些类型的代码或创建特定于域的语言。 Template metaprogramming和元组可以用来自动编写各种繁琐的代码。你也许会意识到模板的钝语法和有限的性能和语义能力意味着它们的成本并不总是被它们提供的好处所抵消。

1

函数模板试图从参数类型中推导出特化类型。

函数模板不能部分专用,而类可以。

函数模板在类可以使用时不能有默认的模板参数。