Trouble with SList for generic Stack class
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 2 16:34:14 PDT 2017
You've probably seen H. S. Teoh's answer but still... :)
On 06/02/2017 04:05 PM, Mark wrote:
> Am I supposed to write template Struct(T) { class Stack { ... } }?
Not necessary because in this case it's the same thing as
class Stack(T) {
// Don't templatize functions in here (in general)
}
However, you can templatize member functions as well if you want them to
work with different types as well. For example, push() may work with any
type that can be converted to T.
class Stack(T) {
private SList!T list;
private int _size;
this() {
// Aside: No need to initialize members (in this case)
// list = SList!T;
// _size = 0;
}
public void push(T item) {
list.insertFront(item);
_size++;
}
public void pop() {
if(_size > 0){
list.removeFront();
_size--;
}
}
// Aside, length() is more idiomatic:
public int length() { return _size; }
}
Ali
More information about the Digitalmars-d-learn
mailing list