2013-03-02 51 views
1
template <int parameter> class MyClass 

是上面的模板专业化吗?我不这么认为,但我不确定,我不知道模板可以接收参数作为函数..他们的参数存储在哪里?这是一个模板专精?

+0

参数存储在哪里?在RAM中。编译期间。 – 2013-03-02 09:25:36

回答

3

模板参数不一定需要是类型名称:它们也可以是数字。例如,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; 
} 
1

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

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

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