c++ template笔记(3)非类型模板参数nontype template parameters

算是模板使用的一种技巧

用模板当数组元素参数维度 

#include template <typename T, int MAXSIZE>
class Stack {private:T elems[MAXSIZE];        // elementsint numElems;            // current number of elementspublic:Stack();                  // constructorvoid push(T const&);      // push elementvoid pop();               // pop elementT top() const;            // return top elementbool empty() const {      // return whether the stack is emptyreturn numElems == 0;}bool full() const {       // return whether the stack is fullreturn numElems == MAXSIZE;}
};// constructor
template <typename T, int MAXSIZE>
Stack::Stack (): numElems(0)               // start with no elements
{// nothing else to do
}template <typename T, int MAXSIZE>
void Stack::push (T const& elem)
{if (numElems == MAXSIZE) {throw std::out_of_range("Stack<>::push(): stack is full");}elems[numElems] = elem;   // append element++numElems;               // increment number of elements
}template<typename T, int MAXSIZE>
void Stack::pop ()
{if (numElems <= 0) {throw std::out_of_range("Stack<>::pop(): empty stack");}--numElems;               // decrement number of elements
}template <typename T, int MAXSIZE>
T Stack::top () const
{if (numElems <= 0) {throw std::out_of_range("Stack<>::top(): empty stack");}return elems[numElems-1];  // return last element
}

使用时就可以根据需要指定最大的元素个数,不用造成资源的浪费

#include 
#include 
#include 
#include "stack4.hpp"int main()
{try {Stack<int,20>         int20Stack;     // stack of up to 20 intsStack<int,40>         int40Stack;     // stack of up to 40 intsStack stringStack;    // stack of up to 40 strings// manipulate stack of up to 20 intsint20Stack.push(7);std::cout << int20Stack.top() << std::endl;int20Stack.pop();// manipulate stack of up to 40 stringsstringStack.push("hello");std::cout << stringStack.top() << std::endl; stringStack.pop();stringStack.pop();}catch (std::exception const& ex) {std::cerr << "Exception: " << ex.what() << std::endl;return EXIT_FAILURE;  // exit program with ERROR status}
}

注意:被实例化出来的int20Stack和int40Stack不可以隐式转换.

模板成员参数

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

特化的参数,用于不在于类型,直接适用于函数中

注意点:浮点类型不可以作为nontype template parameters

以下定义是错误的

//error
template <double T>
double process(double v)
{return v*T;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部