掌握 Linux 下 C++ 模板(Templates)并不是“背语法”,而是循序渐进地理解泛型思想 + 大量实践 + 阅读优秀代码。下面我给你一条从入门到实战的清晰路线,特别适合在 Linux 环境下学习和使用。
C++ 模板主要分为:
Linux 下你还会经常看到:STL、Boost、现代 C++ 库(如 fmt、abseil)
template <typename T>
T max(T a, T b) {
return a > b ? a : b;
}
编译:
g++ -std=c++17 test.cpp -o test
✅ 重点理解:
template <typename T>
class Box {
public:
void set(T v) { value = v; }
T get() { return value; }
private:
T value;
};
使用:
Box<int> b;
b.set(10);
g++ -std=c++17 -Wall -Wextra
模板报错很长,学会看:
with T = ...nm / objdump 看模板生成了什么nm a.out | grep max
template <typename T>
void f(T& x);
int → T = intconst int → T = const inttemplate<>
class Box<bool> {
// 特殊处理
};
template<typename... Args>
void print(Args... args) {
(std::cout << ... << args) << '\n';
}
✅ 写一个:
✅ 阅读源码:
std::vectorstd::shared_ptrfmt 库template<int N>
struct Factorial {
static const int value = N * Factorial<N-1>::value;
};
template<>
struct Factorial<0> {
static const int value = 1;
};
用途:
你可以:
如果你愿意,我可以:
你现在是刚学 C++,还是已经会基础想深入模板?