C++之template

C++模板是一种强大的特性,允许你编写通用的代码。它分为两种类型:函数模板和类模板。

  • 函数模板:可以定义一个函数,使用类型参数。例如:
点击查看代码
  template <typename T>
  T add(T a, T b) {
    return a + b;
  }
  • 类模板:允许你定义一个类,使用类型参数。例如:
点击查看代码
template <typename T>
class Box {
private:
    T item;
public:
    Box(T item) : item(item) {}
    T getItem() { return item; }
};
  • 使用场景:模板非常适合于需要处理多种数据类型的算法和数据结构,如容器类(例如 std::vector)和算法(例如排序、查找)。

更详细的请看

https://www.runoob.com/w3cnote/c-templates-detail.html

posted @ 2024-10-03 10:51  hisun9  阅读(10)  评论(0编辑  收藏  举报