What does template lt;unsigned int Ngt; mean?(模板 unsigned int N 有什么作用?意思是?)
问题描述
在声明模板时,我习惯了这样的代码:
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> 有什么作用?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模板 <unsigned int N> 有什么作用?意思是?


基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09