The code is as follows:
#include <iostream>#include<cstdlib>using namespaceStd;typedefstructTstudent//complete definition of struct body{ intnId; floatFGpa;} Tstudent;template<classT>//template classclasscstroe{ Public: Cstroe (); //constructor FunctionT &getelem ();//return Reference voidPutelem (ConstT &x);//Delivery type ReferencePrivate: T item; //Data BOOLHavevalue;//Control};template<classT> Cstroe<t>::cstroe (): Havevalue (false){}//Constructor InitializationTemplate<classT> t& Cstroe<t>::getelem ()//return Reference{ ////control Switch status if(!havevalue) {cout<<"No Item present!"<<Endl; //exit (1); } returnitem;} Template<classT>voidCstroe<t>::p Utelem (ConstT &trec)//Reference (alias) delivery{Havevalue=true;//Setting the switch statusItem =trec;//}intMain () {//Plastic Examplecstroe<int> nstu1,nstu2;//template classNstu1.putelem (3); Nstu2.putelem (-7); cout<<nstu1.getelem () <<""<<nstu2.getelem () <<Endl; //example of structure typeTstudent tg={ +, at};//Structural BodyCstroe<Tstudent> tS3;//template classTs3.putelem (TG); cout<<"The student ID is"<<ts3.getelem () .nid<<"\ t"<<"Gpa is"<<ts3.getelem () .fgpa<<Endl; //Double Typecstroe<Double>Dstu; cout<<"Retrieving object D ..."; cout<<dstu.getelem () <<Endl; GetChar (); return 0;}
Results:
CFree5 Value Analysis:
Note: Exit (1) in the code snippet, which can be used to indicate the cause of the termination of the program and be accepted by the operating system
Analysis conclusion: Using class template Users can define a pattern for a class so that some data in a class, parameters of a function member, a return value, or a local variable can take any type.
C + + class templates