On Fri, Jun 02, 2017 at 10:21:07PM +0000, Mark via Digitalmars-d-learn wrote:
> Hello,
> 
> I am trying to make a class that can accept any type as an argument.
> 
> Here is the class:
> 
> 
> import std.container: SList;
> 
> 
> class Stack {
> 
>   private SList!T list;
>   private int _size;
> 
>   this(T)() {
>     list = SList!T;
>     _size = 0;
>   }
> 
>   public void push(T)(T item) {
>     list.insertFront(item);
>     _size++;
>   }
> 
>   public void pop(T)() {
>     if(_size > 0){
>       list.removeFront();
>       _size--;
>     }
>   }
> 
>   public int getSize() { return _size; }
> 
> }
> 
> 
> When I compile with dmd, I get this error:
> 
> Stack.d(6): Error: undefined identifier 'T'
> 
> That's on the line private SList!T list;

Yes, because T is not specified when .list is declared.  What you need
to do is to put the template parameter on your class instead of your
methods, something like this:

        class Stack(T) {
                private SList!T list;
                private int _size;

                this() {        // N.B. no template parameter here
                        list = SList!T;
                        _size = 0;
                }

                public void push(T item) { // N.B. no template parameter here
                        ...
                }
                ...
        }


T

-- 
What do you get if you drop a piano down a mineshaft? A flat minor.

Reply via email to