How to declare and define class member functions separately using template.

Hi, I am trying to write a template class, in which member functions are declared with class definition and defined outside class definition.

But getting the following error :


genStack.cpp:44:3: error: prototype for ‘T Stack<T>::push(const T&)’ does not match any in class ‘Stack<T>’
 T Stack<T>::push(const T &x)
   ^~~~~~~~
genStack.cpp:36:14: error: candidate is: void Stack<T>::push(const T&)
         void push(const T &x);



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <vector>
#include <cstring>

using namespace std;


template <typename T>
class Stack
{
    private:
        vector<T> arr;
        int index;
    public:
        Stack(size_t size)
        {
            arr.resize(size);
            index = 0;
        }

        virtual ~Stack() {}

        T pop()				//THIS DEFINITION WORKS FINE
        {
            if (index == 0)
                cout << "Stack empty \n";
            else
            {
                --index;
                return arr.at(index);
            }

            return T(-1);
        }

        void push(const T &x);
/*        {
            arr.at(index++) = x;
            return;
        }*/
};

template <typename T>
T Stack<T>::push(const T &x)		//THIS DEFINITION GIVES ERROR
{
    arr.at(index++) = x;
    return;
}

int main()
{
    Stack<int> iStack(10);

    for (int i = 0; i < 10; ++i)
        iStack.push(i);

    return 0;
}
Last edited on
1
2
T Stack<T>::push(const T&)
void Stack<T>::push(const T&)
¿do you see the difference?

Suppose that T=double
1
2
double Stack<double>::push(const double&)
void Stack<double>::push(const double&)
¿do you see the difference?
Thanks @ne555 for pointing that out :)
Wat a silly mistake :(
Topic archived. No new replies allowed.