C++ 程序中的模板特化?


在本教程中,我们将讨论一个程序,以了解 C++ 中的模板特化。

像 sort() 这样的标准函数可以用于任何数据类型,并且它们对每个数据类型的行为是相同的。但是,如果你想为特定数据类型(甚至是用户定义的)设置函数的特殊行为,我们可以使用模板特化。

示例

 现场演示

#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);
   return 0;
}

输出

The main template fun(): a
Specialized Template for int type: 10
The main template fun(): 10.14

更新时间: 2020 年 3 月 2 日

144 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.