Non-type template parameters

Source: Internet
Author: User

For function templates and class templates, template parameters are not limited to types. common values can also be used as template parameters. In the type parameter-based template, you define some specific details to determine the code until the code is called. However, here, we are faced with values rather than types. To use a value-based template, you must explicitly specify these values to instantiate the template.

Non-type class template parameters

 

Create Class header files

#include<stdexcept>#include<iostream>using namespace std;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 empty() const {        return numElems == 0;    }    bool full() const {        return numElems == MAXSIZE;    }};template<typename T, int MAXSIZE>Stack<T, MAXSIZE>::Stack():numElems(0) {}template<typename T, int MAXSIZE>void Stack<T, MAXSIZE>::push(T const& elem){    if(numElems == MAXSIZE) {        throw out_of_range("Stack<>::push(): stack is full");    }    elems[numElems] = elem;    ++numElems;}template<typename T, int MAXSIZE>void Stack<T, MAXSIZE>::pop(){    if(numElems <= 0) {        throw out_of_range("Stack<>::pop(): stack is full");    }    --numElems;}template<typename T, int MAXSIZE>T Stack<T, MAXSIZE>::top() const{    if(numElems <= 0) {        throw out_of_range("Stack<>::top(): stack is full");    }    return elems[numElems - 1];}

#include<stdexcept>#include<iostream>using namespace std;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 empty() const {        return numElems == 0;    }    bool full() const {        return numElems == MAXSIZE;    }};template<typename T, int MAXSIZE>Stack<T, MAXSIZE>::Stack():numElems(0) {}template<typename T, int MAXSIZE>void Stack<T, MAXSIZE>::push(T const& elem){    if(numElems == MAXSIZE) {        throw out_of_range("Stack<>::push(): stack is full");    }    elems[numElems] = elem;    ++numElems;}template<typename T, int MAXSIZE>void Stack<T, MAXSIZE>::pop(){    if(numElems <= 0) {        throw out_of_range("Stack<>::pop(): stack is full");    }    --numElems;}template<typename T, int MAXSIZE>T Stack<T, MAXSIZE>::top() const{    if(numElems <= 0) {        throw out_of_range("Stack<>::top(): stack is full");    }    return elems[numElems - 1];}

Implementation Code:

#include<iostream>#include<vector>#include<deque>#include<stdexcept>#include<string>#include<cstdlib>#include "stack4.h"using namespace std;int main(){    try {        Stack<int, 20> int20Stack;        Stack<int, 40> int40Stack;        Stack<string, 40> stringStack;                int20Stack.push(7);        cout<<int20Stack.top()<<endl;        int20Stack.pop();        stringStack.push("hello");        cout<<stringStack.top()<<endl;        stringStack.pop();        stringStack.pop();    }    catch(exception const& ex) {        cerr<<"Exception: "<<ex.what()<<endl;        //return EXIT_FAILURE;    }        cin.get();      return 0;}

#include<iostream>#include<vector>#include<deque>#include<stdexcept>#include<string>#include<cstdlib>#include "stack4.h"using namespace std;int main(){    try {        Stack<int, 20> int20Stack;        Stack<int, 40> int40Stack;        Stack<string, 40> stringStack;                int20Stack.push(7);        cout<<int20Stack.top()<<endl;        int20Stack.pop();        stringStack.push("hello");        cout<<stringStack.top()<<endl;        stringStack.pop();        stringStack.pop();    }    catch(exception const& ex) {        cerr<<"Exception: "<<ex.what()<<endl;        //return EXIT_FAILURE;    }        cin.get();      return 0;}

Maxsize is the second newly added template parameter with the int type. It specifies the maximum number of stack elements that an array can contain.
Similarly, we can specify the default value for the template parameters:

template<typename T = int, int MAXSIZE = 100>class Stack {    ...};

  Non-type function template parameters

You can also define non-type parameters for the function template. For example:

template<typename T, int VAL>T addValue(T const& x){    return x + VAL:}

With STL, you can pass the instantiation of this function template to every element in the set, so that they can add an integer:

std::transform(source.begin(), source.end(), dest.begin(), (int(*)(int const&))addValue<int, 5>);

  Non-type template parameter restrictions

Non-type template parameters are limited.Generally, they can be constant integers (including enumeration values) or pointers to external linked objects.

Floating Point Numbers and class objects cannot be used as non-type template parameters:

template<double VAT>double process(double v) //error{    return V * VAT;}template<string name>  //errorclass MyClass {    ...};

In addition, youYou cannot use global pointers as template parameters.:

Template <char const * Name> class myclass {...}; char const * s = "hello"; myclass <S> X; // s is a pointer to an internal connection object.

However, you can use:

template<char const* name>class MyClass {    ...};extern char const s[] = "hello";MyClass<s> x;  //OK

The global character array S is initialized by "hello" and is an external link object.

Non-type template parameters

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.