【发布时间】:2012-09-23 07:02:14
【问题描述】:
我理解这个概念,但我不知道为什么我需要使用非类型模板参数?
【问题讨论】:
我理解这个概念,但我不知道为什么我需要使用非类型模板参数?
【问题讨论】:
有很多用例,让我们来看看它们必不可少的几种情况:
固定大小的数组或matrix 类,例如参见C++11 std::array 或boost::array。
std::begin 用于数组的可能实现,或任何需要固定大小的 C 样式数组大小的代码,例如:
返回数组的大小:
template <typename T, unsigned int N>
unsigned int size(T const (&)[N])
{
return N;
}
它们在模板元编程中也非常有用。
【讨论】:
一个真实的例子来自结合非类型模板参数和模板参数推导来推导数组的大小:
template <typename T, unsigned int N>
void print_array(T const (&arr)[N]) // both T and N are deduced
{
std::cout << "[";
for (unsigned int i = 0; i != N; ++i)
{
if (i != 0) { std::cout << ", ";
std::cout << arr[i];
}
std::cout << "]";
}
int main()
{
double x[] = { 1.5, -7.125, 0, std::sin(0.5) };
print_array(x);
}
【讨论】:
在编译时编程。考虑WikiPedia 的例子,
template <int N>
struct Factorial {
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0> {
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
const int x = Factorial<4>::value; // == 24
const int y = Factorial<0>::value; // == 1
维基百科页面上还有很多其他示例。
如 cmets 中所述,上面的示例演示了 可以做什么,而不是 人们在实际项目中使用什么。
【讨论】:
Bounded Integer 类,但现在找不到。它允许创建自定义类型,例如 bounded<0, 255>。
type conversions 和bounded<int, ...> 与int 一样完美地实现了相同的更完整 实现。
另一个非类型参数的例子是:
template <int N>
struct A
{
// Other fields.
int data[N];
};
这里数据字段的长度是参数化的。此结构的不同实例化可以具有不同长度的数组。
【讨论】: