Funcation Template Help

I am having problems with figuring out how to use templates to take a class and move a char value. I have tried to overload the = operator, but ran into probelms because I don't quite understant how that function works. I run into compile errors on lines 72 and 79. Any help will be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<iostream>
#include<string>
#include<conio.h>
using namespace std;

template<class T>
T askType(T x)
{
	char typeOfThing;
	cout << endl << "Is this animal or vegetable?" << endl;
	cout << "     " << x << endl;
	cout << "Enter A or V" << endl;
	cin >> typeOfThing;
	return(typeOfThing);
}

class Animal
{
	friend ostream& operator<<(ostream& out, Animal a);
		
	public:
		Animal(char n[], int l);
	
	private:
		char name[20];
		int legs;
};

Animal::Animal(char n[], int l)
{
	strcpy_s(Animal::name, n);
	Animal::legs = l;
}

ostream& operator<< (ostream& out, Animal a)
{
	out << a.name;
	return(out);
}

class Vegetable
{
	friend ostream& operator<<(ostream& out, Vegetable v);
		
	public:
		Vegetable(char n[]);
	
	private:
		char name[20];	
};

Vegetable::Vegetable(char n[])
{
	strcpy_s(Vegetable::name, n);
}

ostream& operator<<(ostream& out, Vegetable v)
{
  out << v.name;
  return(out);
}

char askType(char x[20]);

void main()
{
	char ans;
	
	Animal lion("lion",4), snake("snake",0);
	Vegetable carrot("carrot"), onion("onion");

	ans = askType <Animal> ("lion");
	
	if (ans =='A' || ans =='a')
		cout<<("Good!");
	else
		cout<<("Wrong!");
  
	ans = askType <Vegetable> ("carrot");

	if (ans =='V' || ans =='v')
		cout << ("Good!");
	else
		cout << ("Wrong!");
  
  _getch();
}
There is no reason for askType to be a template. In all cases you want it to take a string input and produce a char. You just don't use the type anywhere.
Do you realize that when you call askType <Animal> ("lion");, the compiler generates a function
1
2
3
4
5
6
7
8
9
Animal askType(Animal x)
{
	char typeOfThing;
	cout << endl << "Is this animal or vegetable?" << endl;
	cout << "     " << x << endl;
	cout << "Enter A or V" << endl;
	cin >> typeOfThing;
	return(typeOfThing);
}

I suppose the errors in that are obvious..
your Animal class dont have implicitly constructor but its explicity !!! and cannot convert implicity
"lion" to Animal !! Secondly, in askType you cant return char type instead T type as Animal Type you must return animal type or change type of return function
Topic archived. No new replies allowed.