How to use Template in C ++?

8

I'm learning a bit about template and I made an example, but when I applied to my project I could not, let's go to the following test:

#include <iostream>
using namespace std;

template <class Type>
class p{
public:
     Type setVal(Type i){return i*i;};
private:
    Type dado;
};

int main(){
    p<int> obj;
    p<double> obj2;
    cout << " RESULTADO COM INT "  << obj.setVal(8);
    cout << " RESULTADO COM DOUBLE "  << obj2.setVal(7.4);
    cin.get();
    return 0;
}

In this code I'm creating a class p and in it I'm putting a Type template for its return and for the parameter of it, below I instantiate two objects of the class passing the type of each one and I get the expected result , each of the objects receives the value referring to its type.

Now let's go to the following questions

1 - How do I implement the method outside the class? example:

Type p::setVal(Type i){
    // code goes here
}

2 - (I need to understand 1 before doing 2) adapt the Node / Stack class to  be generic

class No{
public:
    char exp;
    No* prox;
    No(){prox = NULL;}
};


class pilha{
    public:
        pilha();
        void push(char expressao);
        char pop();
        char getTop();
        bool isEmpty();
        bool clear();
        void print();
    private:
    No* topo;
};
    
asked by anonymous 10.04.2015 / 14:42

1 answer

4

To define the methods you need to say that you are using template there as well. Each part is independent:

template <class Type>
Type p<Type>::setVal(Type i){
    // code goes here
}

There you can apply in your example class without much secrecy. Maybe you're thinking that one class needs to be handled in a special way within the other, but it's nothing special, when you instantiate a class as a member inside the other class, just use the parameterized type, everything will be replaced properly by the compiler:

template <class Type>
class No<Type> {
public:
    Type exp;
    No<Type>* prox;
    No<Type>(){prox = NULL;}
};


template <class Type>
class pilha<Type> {
    public:
        pilha();
        void push(Type expressao);
        Type pop();
        Type getTop();
        bool isEmpty();
        bool clear();
        void print();
    private:
    No<Type>* topo; //aqui deve ser sua dúvida, tem que instanciar parametrizado
};

Note that just as I said before that each part is independent, here too it is valid. So the use of Type in the node class and the stack class (this is weird, stack should not have node) is purely coincidental, there is no relation between them. This is not a variable with lifetime in the whole code. It is a placeholder with a life time within the template area that ends at the end of a class or method definition. You could use any word there.

    
10.04.2015 / 15:02