在声明模板时,我习惯了这样的代码:
When declaring a template, I am used to having this kind of code:
template <class T>
但是在这个问题中,他们使用:
template <unsigned int N>
我检查过它可以编译.但是这是什么意思?它是非类型参数吗?如果是这样,我们怎么能有一个没有任何类型参数的模板?
I checked that it compiles. But what does it mean? Is it a non-type parameter? And if so, how can we have a template without any type parameter?
完全可以将类模板化为整数而不是类型.我们可以将模板化的值分配给一个变量,或者以其他任何整数文字的方式对其进行操作:
It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:
unsigned int x = N;
事实上,我们可以创建在编译时进行评估的算法(来自维基百科):
In fact, we can create algorithms which evaluate at compile time (from 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
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
这篇关于模板 <unsigned int N> 有什么作用?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!