How to use Template in C++?

Asked

Viewed 1,324 times

11

I’m learning a little about template and made an example, but when I went to apply to my project I couldn’t, 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 template Type for its return and for its parameter, below I urge two class objects passing the type of each one and 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 out-of-class methods? 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;
};

2 answers

7


To define the methods you need to say you are using template there too. 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 think that one class needs to be treated in a special way within the other, but there is nothing special, when you are instantiating a class as a member within 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
};

I put in the Github for future reference.

Note that in the same way I said before that each part is independent, here also applies. So the use of Type in the knot class and in the stack class (this is weird, stack should not have knot) it is pure coincidence, there is no relationship between them. This is not a lifetime variable across the code. It is a placeholder with lifetime within the area of template that ends at the end of a class or method definition. I could use any word there.

  • 1 test, when I put the template <class Type> above the class and below the setval() function the following msg appears: error: 'template<class Type> class p' used without template parameter

  • code: https://ideone.com/uS4ufd

  • 1

    @Gabrielrodrigues I’m sorry, I forgot to parameterize the same method, I just got it right.

  • I managed to apply in my project

1

In C++ we can use template in:

  • Function
  • Structs
  • Classes

I don’t know about variables and functions, see the examples:

//Devemos usar template antes da declaração.
//O mais comum em template é usar typename que é indefinido, mas pode usar class porém isso
//seria para trabalhar em classes. É colocado entre <>
template <typename I, typename O> O funcao (I valor){
   //Na função ambos podem usar template em parâmetros e retorno. Note que é como estivéssemos
   //declarando uma variável, só que é template.
}

template <class T> class MinhaClasse{
   //Na classe seria a mesma coisa em função, mas usamos em declaração e talvez pode usar em função.
   //Por exemplo estou criando a classe objeto em minha API, semelhante ao Java e C#, temos toString,
   //equals entre outros. Eu posso usar em herança só que na herança use a classe que está herdando
   //em template.
}

template <typename T1, class T2> struct MinhaStruct{
   //Mesma coisa da classe porém é melhor usar typename, algo que preferir.
}

The Amblas received a great mix in C++20, can use template but this is complicated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.