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> 有什么作用?意思是?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07