c++ - 具有专门成员函数的默认模板参数

标签 c++ templates

我有一个类模板 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 ?

最佳答案

由于默认参数,您的专长是

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

关于c++ - 具有专门成员函数的默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50305048/

相关文章:

C++ 重载运算符 < 带有 int 参数(与不保证为 int 的类型相比)

c++ - 如何使用 C++ 中的 Class 函数来保存大数

java - Play 中是否有强制模板参数的语法?

python - Jinja 模板是否有惯用的文件扩展名?

C++ 模板特化问题

c++ - c中的非阻塞输入

c++ - 这是 GCC 中的错误吗?

C++ vector ; remove_if 只删除一个值?

c++ - 模板类中的条件引用声明

c++ - 也接受模板的模板参数(嵌套模板)