我对C++中的模板主题颇为陌生。为什么在下面的玩具示例代码中,我们必须在类和每个函数的名称前加上template <class T>
(这意味着为什么我们需要它)?在声明类和函数时,在C++中使用模板<class T>
是否有可能修改代码不使用template <class T>
无处不在?
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class Stack { private:
vector<T> elements;
public:
void push(T const &);
void pop();
T top();
bool empty(); };
template <class T>
void Stack<T>::push(T const &elem) {
elements.push_back(elem); }
template <class T>
void Stack<T>::pop() {
if (elements.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
} else {
elements.pop_back();
}
}
template <class T>
T Stack<T>::top() {
if (empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
return elements.back();
}
template <class T>
bool Stack<T>::empty() {
return elements.empty();
}
int main() {
try {
Stack<int> intStack; // Stack of ints
Stack<string> stringStack; // Stack of strings
// Manipulate integer stack
intStack.push(7);
cout << intStack.top() << endl;
// Manipulate string stack
stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
}
catch (exception const &ex) {
cerr << "Exception: " << ex.what() << endl;
return -1;
}
}
什么是“模板标题”? – teivaz
模板没有标题。如果你不想使用模板,为两个不同的数据类型'std :: string'和'int'定义两个类。 – P0W
“模板标题”我的意思是'模板'。那么我应该怎么称呼它?我说我对这个话题很陌生。请更容易理解。 –
cerebrou