Please have a look at the following code.
Main.cpp
#include <iostream>
#include "Maximum.h"
using namespace std;
int main()
{
Maximum max;
int int1, int2, int3;
cout << "Input three integers: ";
cin >> int1 >> int2 >> int3;
cout << "The maximum value is: " << max.maximum(int1,int2,int3) << endl;
double double1, double2, double3;
cout << "Input three doubles: ";
cin >> double1 >> double2, double3;
cout << "The maximum value is: " << max.maximum(double1, double2, double3) << endl;
char char1, char2, char3;
cout << "Input three char values: ";
cin >> char1 >> char2 >> char3;
cout << "The maximum value is: " << max.maximum(char1,char2,char3) << endl;
}
Maximum.h
template <class T>
class Maximum
{
public:
Maximum();
T maximum(T value1, T value2, T value3);
};
Maximum.cpp
#include <iostream>
#include "Maximum.h"
Maximum::Maximum()
{
}
T Maximum::maximum(T value1, T value2, T value3)
{
T maximumValue = value1;
if(value2>maximumValue)
{
maximumValue = value2;
}
if(value3>maximumValue)
{
maximumValue = value3;
}
return maximumValue;
}
In maximum.cpp, it gives “‘T’ does not name a type” error. Since it is a user defined one, it might not identified it. How to solve this problem?
Member functions of class templates are themselves templates, and must be defined as such:
Once you’ve fixed that, you’ll probably get some linker errors, because templates must (usually) be defined in every translation unit that uses them. The fix is to move the definitions into the header file. See this question for full details.