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> 有什么作用?意思是?
基础教程推荐
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
