As like the function templates we can define a class template with the help of same syntax we learned in the previous chapter.
Example:
Example:
Header file (classname.h)
}
Source file (classname.cpp)
}
Example:
#include <iostream>
using namespace std;
template<class R> //alternative template<typename R>
class DisplayGreater{
private:
R a,b; //two generic private member variables declared
public:
DisplayGreater(R x, R y) //constructor is used to initialize the variable
:a(x), b(y) //member list initialized
{
}
R Display(){
return (a>b?a:b); //ternary operator is used
}
};
int main() {
DisplayGreater<int> show(10,25); //data type is specified in angle brackets
cout<<show.Display(); //Display function called
return 0;
}
// Output 25
· Here before declaring the class DisplayGreater we initialize the template.
· Then we initialize two generic variables under private access specifier.
· Those variables are then accessed by constructor and initialize them by member initializer list.
· Then we create Display function with data type as R.
· And then we used the ternary operator to find out the bigger value.
· The ternary operator syntax provided here is (a>b?a:b) which is equivalent to the expression if a is greater than b, return a, else, return b.
· In the main function we create an object named show using a different syntax.
· In this case after the class name, datatype is specified within angle brackets in which the function works and make output.
· The Display function returns the greater value of the two member variables.
Class templates for separate class files.
· We already learn how to create separate header and source file for a new class and we also work with them.
· So, now we learn how to implement or use the class template with separate class file.
· A specific syntax is required in case we define our member functions outside of our class.
Example:
Header file (classname.h)
template<class R> //alternative template<typename R>
class DisplayGreater{
private:
R a,b; //two generic private member variables declared
public:
DisplayGreater(R x, R y)
:a(x), b(y) //member list initialized
{
}
R Display(); //Declares the class
Source file (classname.cpp)
template<class R>
R DisplayGreater<int>::Display() //Defines the class and data type is specified in angle brackets
{
return (a>b?a:b); //ternary operator is used
}