How to declare a class template that is placed after the main?

I am trying to implement a template class that is a stack. But I want to declare it before the main one. I can do it? I know that it compiles if you put the main line after the template, but can you put the main one first, then the template?

#include <iostream>


//start declaration of template
template <class T>
class stack<T>;
//end declaration of template
int main() {

    stack<char> s(5);
    s.push('a');
    s.push('b');
    cout <<s.pop()<<endl;
    stack<double> s1(10);
    s1.push(3.2);
    s1.push(0.5);
    cout << s1.pop()<<endl;

    return 0;
}


template <class T>
class stack {
    T *s;
    int size; //How many elements I can stole.
    int top; //Where the index is available.

public: 

    stack(int sz) {
        size = sz;
        s = new T[sz];
        top=-1;
    }

    void push(T e);
    T pop() {

        return s[top--];
    }
};



template <class T>
void stack<T>::push(T e) {

        s[++top] = e;
    }

The given error:

1>.\classTemplPers.cpp(6) : error C2143: syntax error : missing ';' before '<'
1>.\classTemplPers.cpp(6) : error C2059: syntax error : '<'

To record, follow these steps:

template <class T>
class stack;

doesn't work either. I see errors like this:

1>.\classTemplPers.cpp(10) : error C2079: 's' uses undefined class 'stack<T>'
+4
source share
2 answers

The correct syntax for declaring a template is, as Quentin has already pointed out:

template <class T>
class stack;

But this will not help you, because:

Is it possible to first place the main, then the template?

You can only do this if you are not using the template in main.

, , . , . - main, .

+3

. :

template <class T>
class stack;

, , , . - - , .

+2

All Articles