Template class Use Example (i)

Source: Internet
Author: User

The following is a template implementation class for a stack, noting that GCC does not support opening the declaration and definition of a template class (Common class support):

Contents of the TestCC.h file:

#ifndef Testcc_h#defineTestcc_h#include<iostream>#include<vector>#include<stdexcept>Template<typename t>classstack{Private: Std::vector<T>Elems; Public:    voidPush (TConst&); voidpop (); T Top ()Const; BOOLEmpty ()Const    {        returnElems.empty (); }};template<typename t>voidStack<t>::p Ush (TConst&elem) {Elems.push_back (elem);} Template<typename t>voidStack<t>::p op () {if(Elems.empty ()) {ThrowStd::out_of_range ("Stack<>::p op (): Empty Stack"); } elems.pop_back ();} Template<typename t>T Stack<t>::top ()Const{    if(Elems.empty ()) {ThrowStd::out_of_range ("stack<>::top (): Empty Stack"); }    returnelems.back ();}#endif //Testcc_h

Test file Main.cpp:

#include <iostream>#include<string>#include<cstdlib>#include"TestCC.h"using namespacestd;intMain () {Try{Stack<int>IntStack; Intstack.push (7); cout<< intstack.top () <<Endl; Stack<string>StringStack; Stringstack.push ("Hello"); cout<< stringstack.top () <<Endl;        Stringstack.pop ();    Stringstack.pop (); }    Catch(std::exceptionConst&ex) {Cerr<<"Exception:"<< ex.what () <<Endl; returnExit_failure;//In stdlib.h    }}

Results:

Template class Use Example (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.