Search code examples
c++templatesgeneric-programming

C++ - Templates and Data Types


I am very new to C++ and am trying to create a "Generic Class" that can take any input.

I need a way to store whatever input my class receives in either an Array or a Vector. I am however struggling to figure out how to do that.

I tried to do this in my .cpp File:

template<typename T> T data[5];
template<typename T> vector<T> vect;

This is what my Header File looks like:

#include <vector>

using namespace std;

template <class T> class Stack {

public:

    void push(T x);

    T peek();
    T pop();

    int size();
    bool contains();


private:

    vector<T> data;

};

But that is obviously not working, I am given to understand that what I am doing is not possible? How would I be able to create an Array or Vector that can store whatever my class receives?

I am quite new to this, so apologize for silly mistakes and or misunderstandings.


Solution

  • Try this. I have used vector here to store the data. Store this in a .cpp file and compile and execute.

    You had those function declaration. You will get the function bodies here.

    #include<iostream>
    #include<vector>
    using namespace std;
    
    template <class T>
    class Stack{
    private:
        vector<T> elems;
    public:
        void push(T);
        T pop();
        T peek(); 
    };
    
    template<class T>
    void Stack<T>:: push(T obj){
        elems.push_back(obj);
    }
    
    template<class T>
    T Stack<T>::pop(){
        if(!elems.empty()){
            T temp = elems.back();
            elems.pop_back();
            return temp;
        }
    }
    
    template<class T>
    T Stack<T>::peek(){
        if(!elems.empty())
            return elems.back();
    }
    
    int main(){
        Stack<float> S;
        S.push(5.42);
        S.push(3.123);
        S.push(7.1);
        cout << S.pop() << endl;
        S.pop();
        cout << S.peek() << endl;
        return 0;
    }
    

    Output

    7.1
    5.42