简体   繁体   English

具有非数据类型模板参数的类模板专业化

[英]class template specialization with nondatatype template parameter

I have been trying with following code: 我一直在尝试以下代码:

#include <iostream>
using namespace std;

template <typename T, int SIZE>
class Stack
{
        T element;
        T size[SIZE];
        public:
        void  setElement (T elmt)
        {
                element  = elmt;
                cout <<"Inside setElement"<<endl;
        };
        Stack()
        {
                cout <<"Constructor "<<endl;
                cout <<" SIZE is "<<SIZE<<endl;
        }
};

// Int class Specialization.


template<>
class Stack<int>
{  int element;
        int size[SIZE];
        public:
        void  setElement (int elmt)
        {
                element  = elmt;
                cout <<"Inside setElement"<<endl;
        };

        Stack()
        {
                cout <<"Constructor "<<endl;
                cout <<" SIZE is "<<SIZE<<endl;
        }
}


int main(int argc, char ** argv)
{
  Stack<float,50> s;
  Stack<int,20> s1;
}

I have specialized Stack template class to 'int' datatype. 我有专门的堆栈模板类来'int'数据类型。

But i do not know how to bring non-type template parameter 'int SIZE' inside the template while specialise template class? 但是我不知道在专门化模板类的同时如何将非类型模板参数'int SIZE'引入模板中?

I am getting below compilation error: 我收到以下编译错误:

temp1.cpp:26:7: error: too few template arguments for class template 'Stack'
class Stack<int>
      ^
temp1.cpp:5:7: note: template is declared here
class Stack
      ^
temp1.cpp:44:1: error: cannot combine with previous '(error)' declaration specifier
int main(int argc, char ** argv)
^
temp1.cpp:44:5: error: no function template matches function template specialization 'main'
int main(int argc, char ** argv)

How to do this? 这个怎么做?

You are missing the SIZE template parameter on your specialization. 您缺少专业化上的SIZE模板参数。

The template declaration should be : 模板声明应为:

template<int SIZE>
class Stack<int, SIZE>

Live demo here . 现场演示这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM