使用nondatatype模板参数的类模板特化

时间:2014-07-25 06:44:02

标签: c++ templates

我一直尝试使用以下代码:

#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;
}

我有专门的Stack模板类到&#39; int&#39;数据类型。

但我不知道如何使用非类型模板参数&#39; int SIZE&#39;在模板内部专门化模板类?

我遇到编译错误:

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)

怎么做?

1 个答案:

答案 0 :(得分:2)

您缺少专业化的SIZE模板参数。

模板声明应为:

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

现场演示here

相关问题