/Template-Inclusion-Model

A simple example on how to use Templates with the inclusion model

Primary LanguageC++

Template-Inclusion-Model

A simple example on how to use Templates with the inclusion model.

If you are like any other developer, you will want to separate your template class into a declaration file (.h) and an implementation file (.cpp). However, doing so will normally result in a compiler error.

To fix this error you need to #include your implementation file at the end of your header file as shown below:


#ifndef Stack_hpp
#define Stack_hpp

#include <stdio.h>
#include <vector>
#include <stdexcept>
#include <iostream>

template<typename T>

class Stack{
    
    private:
    std::vector<T> elements; //elements of container
    
    public:
    Stack(); //constructor
    
    void push(T const& uElement); //push element
    
    T top()const;   //return top element
};

#include "Stack.cpp"  //#Included the implementation file
#endif


And in your implementation file (.cpp) you will need to use Header guards. I know, you normally use header guards in (.h) files, but this time you will also need to use them in your implementation file. See the snippet below:



#ifndef Stack_cpp  //Header guards 
#define Stack_cpp

#include "Stack.hpp"

template <typename T>
Stack<T>::Stack(){} //constructor

template <typename T>
void Stack<T>::push(T const& uElement){

    elements.push_back(uElement);  //push element into vector

}

template <typename T>
T Stack<T>::top() const{
    
    if (elements.empty()) {
        std::cout<<"Come on dude, I have nothing more to give";
        throw std::out_of_range("Stack<>::top():empty stack");
    }
    
    return elements.back(); //return copy of last element
}

#endif


Now you will be able to use your template in your main.c file:


#include "Stack.hpp"

int main(int argc, const char * argv[]) {

    //create Stack class of type int
    Stack<int> stackOfInts;
    
    //push value 2
    stackOfInts.push(2);
    
    //get last value
    int intValue=stackOfInts.top();
    
    std::cout<<intValue<<std::endl;
    
    return 0;
}


For more information, please see http://www.haroldserrano.com/blog/avoiding-code-duplication-with-class-templates-in-c