阅读量:2
在 Linux 中,C++ 模板的使用与在其他操作系统中的使用相同。模板是 C++ 的一个强大功能,它允许你编写通用的、可重用的代码。模板可以用于函数和类。
以下是一些关于如何在 Linux 中使用 C++ 模板的示例:
- 函数模板
#include
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int a = 5, b = 6;
double c = 7.5, d = 8.5;
std::cout << "整数相加: " << add<int>(a, b) << std::endl;
std::cout << "浮点数相加: " << add<double>(c, d) << std::endl;
return 0;
}
- 类模板
#include
template <typename T>
class Array {
private:
T *data;
int size;
public:
Array(int size) : size(size) {
data = new T[size];
}
~Array() {
delete[] data;
}
void set(int index, T value) {
if (index >= 0 && index < size) {
data[index] = value;
}
}
T get(int index) const {
if (index >= 0 && index < size) {
return data[index];
}
return T();
}
};
int main() {
Array<int> intArray(5);
intArray.set(0, 1);
intArray.set(1, 2);
intArray.set(2, 3);
intArray.set(3, 4);
intArray.set(4, 5);
for (int i = 0; i < 5; ++i) {
std::cout << "intArray["<< i << "] = " << intArray.get(i) << std::endl;
}
Array<double> doubleArray(3);
doubleArray.set(0, 1.1);
doubleArray.set(1, 2.2);
doubleArray.set(2, 3.3);
for (int i = 0; i < 3; ++i) {
std::cout << "doubleArray["<< i << "] = " << doubleArray.get(i) << std::endl;
}
return 0;
}
要编译这些示例,请在终端中使用 g++ 编译器:
g++ -o example example.cpp
然后运行生成的可执行文件:
./example
这将显示模板函数和类的输出。
以上就是关于“Linux中C++如何使用模板”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm