我有一个类模板 stack ,默认模板参数和 pop() 功能,这是专门的成员功能
template <typename T,typename CONT = vector<T> >
class Stack
{
public:
void push(T arg);
T top()const;
void pop();
bool isEmpty() const;
private:
CONT elems_;
};
template <typename T,typename CONT>
void Stack<T,CONT>::pop()
{
elems_.pop_back();
}
// 专门的pop功能
template<>
void Stack<int>::pop()
{
cout << "Called Specialized ";
elems_.pop_back();
}
Main.cpp的
Stack<int> mystack;
mystack.push(10);
mystack.pop(); ---> this calls specialized one Why ?
Stack<int,vector<int>> mystack;
mystack.push(10);
mystack.pop(); ---> this calls template one Why ?
答案 0 :(得分:3)
归功于默认参数,您的专业化是
template<>
void Stack<int, std::vector<int>>::pop()
{
cout << "Called Specialized ";
elems_.pop_back();
}
所以下面都要调用专业化
Stack<int> mystack1; // Stack<int, std::vector<int>>
mystack1.push(10);
mystack1.pop(); // ---> this calls specialized
Stack<int, vector<int>> mystack2;
mystack2.push(10);
mystack2.pop(); // ---> this calls specialized
但非匹配类型会调用泛型:
Stack<int, list<int>> mystack3;
mystack3.push(10);
mystack3.pop(); // ---> this calls generic one
Stack<char> mystack4; // Stack<char, std::vector<char>>
mystack4.push(10);
mystack4.pop(); // ---> this calls generic one