阅读量:2
在C++中,模板是一种泛型编程的工具,它允许你编写与类型无关的代码。模板可以用于函数和类。在Linux环境下使用C++模板的方法与在其他环境下使用相同。
以下是使用模板的一些基本示例:
- 函数模板:
#include
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int a = 1, b = 2;
double c = 3.0, d = 4.0;
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;
}
return 0;
}
在这些示例中,我们使用了typename关键字来定义模板参数。当你实例化一个模板时,编译器会根据你提供的类型生成相应的代码。
要在Linux环境下编译这些示例,请将代码保存到文件中(例如template_example.cpp),然后使用g++编译器编译:
g++ -o template_example template_example.cpp
编译成功后,运行生成的可执行文件:
./template_example
这将显示示例程序的输出。
以上就是关于“Linux C++中如何使用模板”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm