function template

If I could impose and post some code? I'm changing an overloaded initializing function to a template function.

My object code is having: ProgramOneWithMFP.obj : error LNK2019: unresolved external symbol "void __cdecl fnInitialize<int>(int &)" (??$fnInitialize@H@@YAXAAH@Z) referenced in function _main
1>ProgramOneWithMFP.obj : error LNK2019: unresolved external symbol "void __cdecl fnInitialize<double>(double &)" (??$fnInitialize@N@@YAXAAN@Z) referenced in function _main
1>ProgramOneWithMFP.obj : error LNK2019: unresolved external symbol "void __cdecl fnInitialize<char>(char &)" (??$fnInitialize@D@@YAXAAD@Z) referenced in function _main

Please tell me what obvious thing I missed.

ERandall

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
//MFP1.h
	//Declarations:
// What I want to do:

template<class T>
void fnInitialize(T&);

	// What I am replacing:
	
/*void fnInitialize(char&);
	//	a. Initialize variables.
void fnInitialize(double&);
	//	a. Initialize variables.
void fnInitialize(int&);
	//	a. Initialize variables.
void fnInitialize(string&);
	//	a. Initialize variables.*/
	
//MFP1.cpp
	//Definitions: 
	
// Initialize variables (values passed back by reference)
What I want:

template<class T>
void fnInitialize(T &v1)								
{
	v1 = NULL;											// Any variable
}
Replacing:

/*void fnInitialize(string &str)
{
	str = "";											// string
}

void fnInitialize(int &a)
{
	a = 0;												// Integer
}

void fnInitialize(double &d)
{
	d = 0.00;											// Double
}*/

//The call from Main.cpp

// Intialize the variables through pass-by-reference (set in prototype)
	fnInitialize(chGender);
	fnInitialize(dGPA);
	fnInitialize(nFemaleCount);
	fnInitialize(nMaleCount);
	fnInitialize(dFemaleSum);
	fnInitialize(dMaleSum);

Templates aren't like normal functions -- you can't split the declaration and the definition; you have to put it all in the header file.

Read the very bottom of this page:
http://www.cplusplus.com/doc/tutorial/templates/

EDIT: Oh, and if you wanted to initialize everything to its default value (0 for numeric types, empty string for strings, etc.), you should probably do:
1
2
3
4
5
template <class T>
void initialize(T& v1)
{
    v1 = T();
}

because what you have right now won't work for a std::string.
(you can't set a std::string to NULL).
Last edited on
ldm,
Thanks for that. I'm going to put declarations and definitions in my header file anyhow, at least the transferable ones. The initializing code is greatly appreciated.
Put it in MFP1.h and it builds without issues.
Last edited on
Topic archived. No new replies allowed.