C++ 中的泛型

泛型是允许类型(整数、字符串等和用户定义类型)成为方法、类和接口的参数的想法。例如,数组、映射等类可以非常有效地使用泛型。我们可以将它们用于任何类型。

实现了泛型编程的方法来提高代码的效率。通用编程使程序员能够编写适用于所有数据类型的通用算法。如果数据类型是整数、字符串或字符,则无需创建不同的算法。

泛型编程的优点是

代码可重用性
避免函数重载
一旦写入,就可以多次使用和案例。
泛型可以使用Templates在 C++ 中实现。Template 是 C++ 中一个简单但非常强大的工具。简单的想法就是将数据类型作为参数传递,这样我们就不需要为不同的数据类型编写相同的代码。例如,软件公司可能需要对不同数据类型进行 sort()。我们可以编写一个 sort() 并将数据类型作为参数传递,而不是编写和维护多个代码。

使用模板的通用函数:
我们编写一个可用于不同数据类型的通用函数。函数模板的示例有 sort()、max()、min()、printArray()

#include <iostream>
using namespace std;
  
// One function works for all data types.
// This would work even for user defined types
// if operator '>' is overloaded
template <typename T>
  
T myMax(T x, T y)
{
    return (x > y) ? x : y;
}
  
int main()
{
  
    // Call myMax for int
    cout << myMax<int>(3, 7) << endl;
  
    // call myMax for double
    cout << myMax<double>(3.0, 7.0) << endl;
  
    // call myMax for char
    cout << myMax<char>('g', 'e') << endl;
  
    return 0;
}

输出:

7
7
G

使用模板的通用类:
与函数模板一样,当类定义独立于数据类型的内容时,类模板非常有用。对于 LinkedList、二叉树、Stack、Queue、Array 等类很有用。

以下是模板 Array 类的简单示例。

#include <iostream>
using namespace std;
  
template <typename T>
class Array {
private:
    T* ptr;
    int size;
  
public:
    Array(T arr[], int s);
    void print();
};
  
template <typename T>
Array<T>::Array(T arr[], int s)
{
    ptr = new T[s];
    size = s;
    for (int i = 0; i < size; i++)
        ptr[i] = arr[i];
}
  
template <typename T>
void Array<T>::print()
{
    for (int i = 0; i < size; i++)
        cout << " " << *(ptr + i);
    cout << endl;
}
  
int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    Array<int> a(arr, 5);
    a.print();
    return 0;
}

输出:

1 2 3 4 5

使用多类型泛型:
我们可以将不止一种数据类型作为参数传递给模板。以下示例演示了相同的内容。

#include <iostream>
using namespace std;
  
template <class T, class U>
class A {
    T x;
    U y;
  
public:
    A()
    {
        cout << "Constructor Called" << endl;
    }
};
  
int main()
{
    A<char, char> a;
    A<int, double> b;
    return 0;
}

输出:
构造函数被调用
构造函数被调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Q shen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值