【问题标题】:Class Template Specialisation, C++, mismatch at argument 2 in template parameter list类模板专业化,C++,模板参数列表中的参数 2 不匹配
【发布时间】:2016-10-08 12:21:04
【问题描述】:

我有一个模板:

template <typename T, int size>
class Array
{

    T A[size];

public:

    T& operator[](int index) ;

};

template <typename T, int size>
T& Array<T,size>::operator[](int index)
{
    if (index>=size || index<0)
        return A[0];
    else
        return A[index];
}

及其特化类:

typedef struct Data
{
    int id;
    char name[10];
    double temp;
    double quantity;
}Data;

template <>
class Array<Data, int>
{
};

我尝试使用它:

int main()
{
    Array<Data, int> tab;
    return 0;

}

但是我收到了这个错误,我真的不知道为什么:

错误:模板参数列表中参数 2 的类型/值不匹配 对于‘模板类数组’|

怎么了?

这很奇怪。我将代码更改为以下代码:

template <>
class Array<Data, 20>
{
};

int main()
{
    Array<Data, 20> tab;
    return 0;
}

现在可以了。谢谢!

【问题讨论】:

  • 您的第二个模板参数需要int,而不是类型。
  • @tkausl:当我删除int时,错误变为error: wrong number of template arguments (1, should be 2)|error: provided for ‘template&lt;class T, int size&gt; class Array’|

标签: c++ templates


【解决方案1】:

我只能猜测您实际上想要为 Array&lt;T, size&gt; 创建模板专业化,其中未指定 T=Datasize

template <int size>
class Array<Data, size> // partial specialization
{
};

当你实例化模板时,你必须指定一个常量大小:

int main()
{
    Array<Data, 5> tab; // size=5 for this example
    return 0;
}

【讨论】:

  • 是的,就是这样!非常感谢!我这里只有一个问题:我可以在 Array&lt;Data, size&gt; 类 co 中添加一个构造函数,我可以初始化 Data 结构的成员吗?
  • @BrianBrown 当你创建一个类专业化时,你基本上重写了整个类!当然你可以在那里写一个特殊的构造函数。当您不想想要为特殊化重写模板类的某些部分时,实际问题可能会出现。 This question 可能会变得相关。
猜你喜欢
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
相关资源
最近更新 更多