Upgrade the following code to make it a template for classes of any specified type and any specified size.

Question 

Upgrade the following code to make it a template for classes of any specified type and any specified size.

class QueueItem{
std::string complain_type;
std:: string customer_id;
public:
QueueItem(){}
QueueItem(const std::string& aa, const std::string& bb){
complain_type = aa;
customer_id = bb;
}
const std::string& key() const{return complain_type;}
const std::string& value() const{return customer_id;}
void display(std::ostream& os) const{
os <<complain_type << ": "<< customer_id <<std::endl;

 

Summary

What is a template:

The template is defined as a blueprint or formula for creating a generic class or a function. It is a simple idea to pass data type as a parameter so that we don’t need to write the same code for different data types. Templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code C++ provides two kinds of template for classes:

1) Class templates

2) Generic templates.

Templates are  explained with the below diagram;

template for classes

 

Explanation

Initially, we need to declare the header files for the program. And then define the template with keyword template of typename S.

The next step is to define a class QItem inside the template and declare the variables ctype and cid.

And then create a constructor of the same class name Qitem and initialize the values for ctype and cid.

After that declare and define methods like key(),val(),and disp() of void prototype.
In the main function create an obj for the class and using that obj call the methods key and val.

Next, initiate an ostream obj and with that obj call the method disp() with specific parameters.

 

Code:

#include <iostream>
#include<ostream>
#include<string>
using namespace std;
//Defining a template typename S
template <typename S>
//Defining a class QItem inside the  template S
class QItem{
    S ctype;
    S cid;
    public:
    QItem(S aa, S bb){
        ctype=aa;
        cid=bb;
    }
    S key(){
        return ctype;
    }
    S val(){
        return cid;
    }
    void disp(std::ostream &os){
        os<<ctype<<":"<<cid<<endl;
    };
};
int main()
{
    QItem<string> Q("General","c1");
    cout<<Q.key()<<endl<<Q.val()<<endl;
    std::ostream & os = std::cout;
    Q.disp(os);
}

 

Output

template for classes

 

Also, read our other blog which is to write a relational schema for the diagram.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *