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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP