c++ - 什么时候写模板尖括号(<...>)?

标签 c++ class templates

给定这个示例类模板:

template<typename T>
class Stack {
    T * data;
    int size;
    int nextIndex;
public:
    Stack(int size = 100);
    Stack(const Stack& stack);
    ~Stack();
    Stack& operator=(const Stack& s);
    void push(const T& t);
    void pop();
    T& top();
    const T& top() const;
    int getSize() const;

    class Full {
    };
    class Empty {
    };
};

template<typename T>
void Stack::push(const T& t) {
    if (nextIndex >= size) {
        throw Full();
    }
    data[nextIndex++] = t;
}
 
template<typename T>
void Stack::pop() {
    if (nextIndex <= 0) {
        throw Empty();
    }
    nextIndex--;
}  

push 的实现部分可以吗?和 pop方法?

不明白要不要写void Stack<T>::push(const T& t)而不是 void Stack::push(const T& t) (对于 pop 方法也是如此)。

注意:Eclipse(根据 C++11)给我下一个错误:

Member declaration not found

因为这些行:

void Stack::push(const T& t) { 
void Stack::pop() {

最佳答案

The part of the implementaion of push method and pop method it's ok? I don't understand if I need to write void Stack::push(const T& t) instead void Stack::push(const T& t) (and the same for pop method).

你需要使用

template <typename T>
void Stack<T>::push(const T& t) { ... }

template <typename T>
void Stack<T>::pop() { ... }

名字StackStack<T>相同当它用作类型名时,在类模板定义中。在类模板定义之外,您必须显式提供模板参数。

关于c++ - 什么时候写模板尖括号(<...>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49285264/

相关文章:

c++ - 有选择地编译宏外部的代码

c++ - 在 C++ 中传递回调函数参数的最佳方法

c++ - 方法 ('Vector' 的命名空间和模板类 vector 声明未命名类型;你是说 'perror' 吗?)

C++ 如何获得 sizeof(enum) == sizeof(char)?

java - 无法理解如何创建链表数组

class - VueJS - 如何从 v-for 创建的对象绑定(bind)多个类?

JavaScript:调用类对象的函数将值添加到对象数组中

visual-studio - VS2013 和 Azure - 部署模板验证失败,尽管我既没有编辑模板也没有编辑项目属性

c++ - shared_ptr 和 unique_ptr 转换

c++ - C++ 数学库的三角函数的结果不正确