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;
};
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
– Gabriel Rodrigues
code: https://ideone.com/uS4ufd
– Gabriel Rodrigues
@Gabrielrodrigues I’m sorry, I forgot to parameterize the same method, I just got it right.
– Maniero
I managed to apply in my project
– Gabriel Rodrigues