在 Ubuntu 下使用 C++ 模板类(template class)和在其他 Linux / 平台上是一样的,主要依赖 g++ 编译。下面从基本语法、使用方式、编译方法、常见坑几个方面讲清楚。
Stack.h
#ifndef STACK_H
#define STACK_H
#include <vector>
template <typename T>
class Stack {
public:
void push(const T& value) {
data.push_back(value);
}
T pop() {
T val = data.back();
data.pop_back();
return val;
}
bool empty() const {
return data.empty();
}
private:
std::vector<T> data;
};
#endif
main.cpp
#include "Stack.h"
#include <iostream>
int main() {
Stack<int> s;
s.push(10);
s.push(20);
std::cout << s.pop() << std::endl;
return 0;
}
g++ main.cpp -o test
./test
✅ 模板类一般不需要单独编译成 .o 文件
因为:
Stack<int> 时需要看到完整定义❌ 错误示例(常见坑):
// Stack.cpp 里写模板实现
template class Stack<int>; // 必须显式实例化
✅ 推荐方式:
.h.hpp如果你一定要分开写:
template <typename T>
class Stack {
public:
void push(const T& value);
};
#include "Stack.h"
#include <vector>
template <typename T>
void Stack<T>::push(const T& value) {
// 实现
}
// 显式实例化
template class Stack<int>;
template class Stack<double>;
编译:
g++ main.cpp Stack.cpp -o test
⚠️ 不推荐,除非你只用固定类型
g++ --version
建议:
g++ -std=c++11g++ -std=c++17Stack s; // 错误
Stack<int> s; // 正确
templatetemplate <typename T>
void Stack<T>::push(...) { }
✅ 模板类适合:
✅ Ubuntu 开发常用组合:
如果你愿意,我可以:
你可以直接说你现在是「初学 / 写项目 / 刷题 / 面试」。