在 Ubuntu 下使用 C++ 模板,你需要遵循以下步骤:
- 安装编译器:确保你已经安装了 GCC(GNU Compiler Collection)和 G++(GNU C++ Compiler)。如果没有,请使用以下命令安装:
sudo apt-get update sudo apt-get install build-essential
-
创建一个 C++ 源文件:使用文本编辑器创建一个新的 C++ 源文件,例如
main.cpp
。在这个文件中,你可以编写包含模板的代码。 -
编写模板代码:在
main.cpp
文件中,编写你的模板代码。模板可以用于函数和类。以下是一个简单的函数模板示例:
#includetemplate T add(T a, T b) { return a + b; } int main() { int x = 5, y = 10; double a = 3.5, b = 4.5; std::cout << "Sum of integers: " << add (x, y) << std::endl; std::cout << "Sum of doubles: " << add (a, b) << std::endl; return 0; }
- 编译和运行代码:在终端中,导航到包含
main.cpp
文件的目录,然后使用以下命令编译和运行代码:
g++ -o main main.cpp ./main
这将输出:
Sum of integers: 15 Sum of doubles: 8
这就是在 Ubuntu 下使用 C++ 模板的基本方法。你可以根据需要修改和扩展这个示例,以满足你的需求。