什么是template< unsigned int N>意思? [英] What does template <unsigned int N> mean?

查看:1205
本文介绍了什么是template< unsigned int N>意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当声明模板时,我习惯使用这种代码:

When declaring a template, I am used to having this kind of code:

template <class T>

But in this question, they used:

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;

事实上,我们可以创建在编译时评估的算法(从 Wikipedia ):

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
}

这篇关于什么是template&lt; unsigned int N&gt;意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆