【问题标题】:Is this a template specialization? [duplicate]这是模板专业化吗? [复制]
【发布时间】:2013-03-02 09:19:11
【问题描述】:
template <int parameter> class MyClass

以上是模板特化吗?我不这么认为,但我不确定,我不知道模板可以将参数作为函数接收。它们的参数存储在哪里?

【问题讨论】:

  • 参数存储在哪里?在内存中。编译期间。

标签: c++ templates


【解决方案1】:

模板参数不一定是类型名称:它们也可以是数字。例如,std::array 采用 size_t 类型的参数作为数组大小。

在您的情况下,类模板采用int 类型的参数,这完全可以。以下是如何使用此类参数的示例:

template <int param> struct MyClass {
    int array[param]; // param is a compile-time constant.
};
int main() {
    MyClass<5> m;
    m.array[3] = 8; // indexes 0..4 are allowed.
    return 0;
}

【讨论】:

    【解决方案2】:

    它们的参数存储在它们的类型信息中。

    不,这不是模板专业化。看看这个:

    template <int, int> class MyClass;         // <-- primary template
    template <int>      class MyClass<int, 4>; // <-- partial specialization
    template <>         class MyClass<5, 4>;   // <-- specialization
    

    【讨论】:

      猜你喜欢
      • 2015-10-24
      • 2014-10-08
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多