C ++中的模板专业化
在C++中,模板用于创建通用的函数和类。因此,我们可以使用模板使用任何类型的数据,例如int,char,float或某些用户定义的数据。
在本节中,我们将看到如何使用模板专门化。因此,现在我们可以为不同类型的数据定义一些通用模板。还有一些特殊的模板功能,用于特殊类型的数据。让我们看一些例子以获得更好的主意。
范例程式码
#include<iostream>
using namespace std;
template<typename T>
void my_function(T x) {
cout << "This is generalized template: The given value is: " << x << endl;
}
template<>
void my_function(char x) {
cout << "This is specialized template (Only for characters): The given value is: " << x << endl;
}
main() {
my_function(10);
my_function(25.36);
my_function('F');
my_function("Hello");
}输出结果
This is generalized template: The given value is: 10 This is generalized template: The given value is: 25.36 This is specialized template (Only for characters): The given value is: F This is generalized template: The given value is: Hello
也可以为类创建模板专用化。让我们通过创建通用类和专用类来查看一个示例。
范例程式码
#include<iostream>
using namespace std;
template<typename T>
class MyClass {
public:
MyClass() {
cout << "This is constructor of generalized class " << endl;
}
};
template<>
class MyClass <char>{
public:
MyClass() {
cout << "This is constructor of specialized class (Only for characters)" << endl;
}
};
main() {
MyClass<int> ob_int;
MyClass<float> ob_float;
MyClass<char> ob_char;
MyClass<string> ob_string;
}输出结果
This is constructor of generalized class This is constructor of generalized class This is constructor of specialized class (Only for characters) This is constructor of generalized class
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短