非类型的类模板参数

//main.cpp

#include "pch.h"
#include <iostream>
#include "stack1.h"
#include<string>
using namespace std;
int main()
{
    
    
	//类的非类型模板参数
	_space3::stack<int, 10>  sint10;
	for (int i = 0; i < 10; i++)
	{
    
    
		sint10.push(i);
	}
	cout << sint10.top() << endl;
	//
	sint10.pop();
	cout << sint10.top() << endl;
	//非类型模板参数的限制
	//int o = 20;
	//_space3::stack<int, o>  sint10;//不可以,必须是常量值
	return 0;
}

//stack1.h

#include "pch.h"
#include<vector>
#include<deque>
using namespace std;
namespace _space3
{
    
    
	//template<typename T, double MAXSIZE> //不能是浮点类型的,类对象也是不可以,或许以后可以
	//这是非类型模板参数的一些限制
	template<typename T, int MAXSIZE>
	class stack
	{
    
    
	private:
		int numls;
		T elems[MAXSIZE];
	public:
		stack() :numls(0)
		{
    
    
			cout << "stack() :numls(0)" << endl;
		}
	public:
		bool empty() const
		{
    
    
			if (numls == 0)
			{
    
    
				cout << "没有元素!" << endl;
			}
		}

		//压栈
		void push(T const& emls)
		{
    
    
			if (numls == MAXSIZE)
			{
    
    
				cout << "栈满,无法压栈" << endl;
				return;
			}
			elems[numls] = emls;
			numls++;
		}

		//出栈
		void pop()
		{
    
    
			numls--;
		}

		//返回栈顶元素
		T top() const
		{
    
    
			return elems[numls - 1];
		}
	};
}

猜你喜欢

转载自blog.csdn.net/qq_38158479/article/details/114219198