侧边栏壁纸
  • 累计撰写 218 篇文章
  • 累计创建 59 个标签
  • 累计收到 5 条评论

C++ 基于 template 的泛型

barwe
2022-08-29 / 0 评论 / 0 点赞 / 658 阅读 / 587 字
温馨提示:
本文最后更新于 2022-08-29,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

在 JavaScript 中我们这样使用 泛型

function sum<T>(x: T, y: T) {
    return x + y;
}

console.log(sum(1,2)) //=> 3
console.log(sum('x','y')) //=> xy

在 C++ 中我们通过 template 关键字声明 泛型

template <typename T> T const& sum(T const& x, T const& y) {
    return x + y;
}

cout << sum(1, 2) << endl; //=> 3
cout << sum(1.1, 2.2) << endl; //=> 3.3

有时候太长了就拆成两行写:

template <typename T>
T const& sum(T const& x, T const& y) {
    return x + y;
}

简单函数可以使用 inline 关键字,建议编译器将该函数内联(减少函数调用次数):

template <typename T>
inline T const& sum(T const& x, T const& y) {
    return x + y;
}

使用 template 声明 泛型

template <typename T>
class MyClass {}
0

评论区