在Linux下使用C++进行模板编程,你需要遵循以下步骤:
sudo apt-get update
sudo apt-get install g++
template_example.hpp的头文件,并在其中编写模板代码。例如:#ifndef TEMPLATE_EXAMPLE_HPP
#define TEMPLATE_EXAMPLE_HPP
template <typename T>
T add(T a, T b) {
return a + b;
}
#endif // TEMPLATE_EXAMPLE_HPP
main.cpp的源文件,并在其中编写使用模板的代码。例如:#include <iostream>
#include "template_example.hpp"
int main() {
int a = 5;
int b = 10;
std::cout << "Addition of integers: " << add<int>(a, b) << std::endl;
double c = 3.14;
double d = 2.59;
std::cout << "Addition of doubles: " << add<double>(c, d) << std::endl;
return 0;
}
g++ -std=c++11 main.cpp -o template_example
这里,-std=c++11选项告诉编译器使用C++11标准。你可以根据需要替换为其他C++标准,如C++14、C++17等。
./template_example
输出结果应为:
Addition of integers: 15
Addition of doubles: 5.73
这就是在Linux下使用C++进行模板编程的基本过程。你可以根据需要编写更复杂的模板代码,并在不同的项目中重用它们。