在 Linux 下使用 C++ 模板(Template)和在其他平台(Windows/macOS)本质上是一样的,因为模板是 C++ 语言标准的一部分,不依赖操作系统。差别只在于 编译工具链(如 g++ / clang++) 和开发环境。
下面从 基础 → 进阶 → Linux 下编译实践 给你一个完整说明。
模板用于 泛型编程,让代码不依赖具体类型。
两类最常见:
#include <iostream>
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << add(1, 2) << std::endl;
std::cout << add(1.5, 2.5) << std::endl;
return 0;
}
g++ test.cpp -o test
./test
#include <iostream>
template <typename T>
class Box {
private:
T value;
public:
Box(T v) : value(v) {}
T get() { return value; }
};
int main() {
Box<int> intBox(10);
Box<std::string> strBox("hello");
std::cout << intBox.get() << std::endl;
std::cout << strBox.get() << std::endl;
}
⚠️ 重要规则:
模板代码一般必须放在
.h或.hpp文件中,不能只放在.cpp里
❌ 错误示例(链接错误):
// foo.cpp
template <typename T>
void foo(T x) {}
✅ 正确:
// foo.h
template <typename T>
void foo(T x) {
// 实现
}
#ifndef FOO_H
#define FOO_H
template <typename T>
T max(T a, T b);
#include "foo.tpp"
#endif
template <typename T>
T max(T a, T b) {
return a > b ? a : b;
}
#include "foo.h"
#include <iostream>
int main() {
std::cout << max(3, 5) << std::endl;
}
如果你 非要把模板实现放 cpp,可以显式实例化:
// foo.cpp
template int max<int>(int, int);
但不够灵活,不推荐新手用。
g++ -std=c++17 main.cpp -o app
或 clang:
clang++ -std=c++20 main.cpp -o app
❌ undefined reference to ...
template<typename... Args>
void print(Args... args) {
(std::cout << ... << args) << std::endl;
}
✅ Linux 下使用 C++ 模板:
g++ / clang++如果你愿意,我可以:
你更想看哪一块?