C++中的模板 这是一个特点。我们只编写一次代码,并将其用于任何数据类型,包括用户定义的数据类型。例如,可以编写sort()并用于对任何数据类型的项进行排序。可以创建一个类堆栈,它可以用作任何数据类型的堆栈。 如果我们想为特定的数据类型使用不同的代码呢? 考虑一个需要多个不同数据类型数组的函数Stand()的大项目。让快速排序用于除char之外的所有数据类型。对于char,总的可能值是256,计数排序可能是更好的选择。只有在为char数据类型调用sort()时,才能使用不同的代码吗? C++中可以为特定数据类型获得特殊行为。这被称为模板专门化 .
CPP
// A generic sort function template < class T> void sort(T arr[], int size) { // code to implement Quick Sort } // Template Specialization: A function // specialized for char data type template <> void sort< char >( char arr[], int size) { // code to implement counting sort } |
另一个例子可能是一个类 设置 它表示一组元素,并支持并集、交集等操作。当元素类型为char时,我们可能需要使用大小为256的简单布尔数组来创建一个集合。对于其他数据类型,我们必须使用其他一些复杂的技术。 函数模板专门化的示例程序 例如,考虑下面的简单代码,其中除了INT之外,对于所有数据类型都有通用模板Fund()。对于int,有一个专门的Fund()版本。
CPP
#include <iostream> using namespace std; template < class T> void fun(T a) { cout << "The main template fun(): " << a << endl; } template <> void fun( int a) { cout << "Specialized Template for int type: " << a << endl; } int main() { fun< char >( 'a' ); fun< int >(10); fun< float >(10.14); } |
输出:
The main template fun(): aSpecialized Template for int type: 10The main template fun(): 10.14
类模板专门化的示例程序 在下面的程序中,为int数据类型编写了一个特殊版本的类测试。
CPP
#include <iostream> using namespace std; template < class T> class Test { // Data members of test public : Test() { // Initialization of data members cout << "General template object " ; } // Other methods of Test }; template <> class Test < int > { public : Test() { // Initialization of data members cout << "Specialized template object" ; } }; int main() { Test< int > a; Test< char > b; Test< float > c; return 0; } |
输出:
Specialized template objectGeneral template objectGeneral template object
模板专门化是如何工作的? 当我们编写任何基于模板的函数或类时,只要编译器看到该函数/类被用于一个新的数据类型或一组新的数据类型(在多个模板参数的情况下),编译器就会创建该函数/类的副本。 如果存在专用版本,编译器首先检查专用版本,然后检查主模板。编译器首先通过将传递的参数与专用版本中指定的数据类型匹配来检查最专用的版本。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论