具有2或1个模板参数的相同类

时间:2009-05-26 22:04:01

标签: c++ templates specialization

如何制作一个模板专业化,其中2个参数与普通1相比? 我正在构建一个指针类,现在我想扩展到一个数组,但如果我尝试这样的东西:

template<class T,int s> class pointer{};
template<class T> class pointer{};

class mama{};
int main(){
    pointer<mama> m;
}

它给了我一个错误。模板...用1个参数重新声明。

我需要它专门,因为pointer<mama,10>有size()和operator []而pointer<mama>没有,它有operator-&gt;和*。

3 个答案:

答案 0 :(得分:8)

您可以为数组案例制作一般模板:

template <class TElem, int size = 0>
class pointer
{
    // stuff to represent an array pointer
};

然后是部分专业化:

template <class TElem>
class pointer<TElem, 0>
{
    // completely different stuff for a non-array pointer
};

通过为size = 0的情况定义一个专用版本,你实际上可以给出一个完全不同的实现,但名称相同。

然而,仅仅给它一个不同的名称可能更清楚。

答案 1 :(得分:3)

您的代码中有类模板重新声明,这将导致编译时错误。您可以拥有默认模板参数和模板模板参数。

template<class T,int s=10> class pointer{};

class mama{};
int main(){
    pointer<mama> m;
}
  

我需要它专门,因为指针有size()和operator []而指针没有,它有operator-&gt;和*。

您的班级看起来好像需要不同的设计。我不确定模板专业化是否可行。从问题的外观来看,你真的应该考虑基于特征的专业化。

答案 2 :(得分:2)

您可以为第二个参数设置默认值,可能是这样的:

template <class T, int N=0>
class moo {
        T *foo;
public:
        moo() {
                if (N > 0) {
                        foo = new T[N];
                }
                else
                {
                        foo = new T;
                }
        }
};