The emergence of the C ++ programming language immediately attracted the attention of developers. It has the functions used in the C language and supports many programming styles. Today, we will introduce some basic concepts of C ++ non-type template parameters, so that you can have a deeper understanding of this content.
In my opinion, the C ++ non-type class template parameter is equivalent to a global constant role. The following example is used to describe non-type class templates. By redefining a Stack template, this chapter requires a fixed-size array as the element container, and the size of the array can be defined by the template user. Therefore, the template designer should provide an interface for users to define the size of the array. This requires non-type class template parameters. The following code can be used to explain this problem:
- # Include <iostream>
- # Include <string>
- # Include <cstdlib>
- # Include <stdexcept>
- Template <typename T, int MAXSIZE>
- Class Stack {
- Private:
- T elems [MAXSIZE];
- Int numElems;
- Public:
- Stack ();
- Void push (T const &);
- Void pop ();
- T top () const;
- Bool isEmpty () const {
- Return numElems = 0;
- }
- Bool isFull () const {
- Return numElems = MAXSIZE;
- }
- };
- Template <typename T, int MAXSIZE>
- Stack <T, MAXSIZE >:: Stack (): numElems (0)
- {
- // Do not do anything, just to initialize numElems.
- }
- Template <typename T, int MAXSIZE>
- Void Stack <T, MAXSIZE >:: push (T const & elem)
- {
- If (numElems = MAXSIZE)
- {
- Throw std: out_of_range ("Stack <>:: push () ==> stack is full .");
- }
- Elems [numElems] = elem;
- ++ NumElems;
- }
- Template <typename T, int MAXSIZE>
- Void Stack <T, MAXSIZE >:: pop ()
- {
- 47 if (numElems <= 0)
- {
- Throw std: out_of_range ("Stack <>:: pop: empty stack ");
- }
- -- NumElems;
- }
- Template <typename T, int MAXSIZE>
- T Stack <T, MAXSIZE >:: top () const
- {
- If (numElems)
- {
- Throw std: out_of_range ("Stack <>:: pop: empty stack ");
- }
- // Return the last element.
- Return elems [numElems-1];
- }
- Int main ()
- {
- Try
- {
- Stack <int, 20> int20Stack;
- Stack <int, 40> int40Stack;
- Stack <std: string, 40> stringStack;
- Int20Stack. push (7 );
- Std: cout <"int20Stack. top ():" <int20Stack. top () <std: endl;
- Int20Stack. pop ();
- StringStack. push ("HelloWorld! ");
- Std: cout <"stringStack. top ():" <stringStack. top () <std: endl;
- StringStack. pop ();
- StringStack. pop ();
- }
- Catch (std: exception const & ex)
- {
- Std: cerr <"Exception:" <ex. what () <std: endl;
- Return EXIT_FAILURE;
- }
- Return 0;
- }
The code above reveals the definition and usage of C ++ non-type class template parameters.