非类型模板数组
Nontype Template Array
是否可以将数组作为非类型模板参数传递?
例如
template<typename T, T> struct s;
template<typename T, size_t S, T A[S]> struct s<T[S], A>
{ };
是的,这是可能的,这是一个在 C++11 及更高版本中有效的示例:
#include <cstddef>
template<typename T, size_t S, T A[S]>
struct s
{
static constexpr auto x = A[1];
};
static constexpr int a[3] = {10,20,30};
int f()
{
return s<const int, 3, a>::x;
}
f()
returns 20,如下所示:https://godbolt.org/z/GggQd9
参考 the draft C++17 standard §17.1.4.2 [temp.param]:
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- pointer to object or pointer to function,
和§17.1.4.8:
A non-type template-parameter of type “array of T” or of function type T is adjusted to be of type “pointer to T”
最终结果是你的T A[S]
声明等同于T* A
,并且允许指向对象的指针,数组是对象,所以代码是有效的。
是否可以将数组作为非类型模板参数传递?
例如
template<typename T, T> struct s;
template<typename T, size_t S, T A[S]> struct s<T[S], A>
{ };
是的,这是可能的,这是一个在 C++11 及更高版本中有效的示例:
#include <cstddef>
template<typename T, size_t S, T A[S]>
struct s
{
static constexpr auto x = A[1];
};
static constexpr int a[3] = {10,20,30};
int f()
{
return s<const int, 3, a>::x;
}
f()
returns 20,如下所示:https://godbolt.org/z/GggQd9
参考 the draft C++17 standard §17.1.4.2 [temp.param]:
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- pointer to object or pointer to function,
和§17.1.4.8:
A non-type template-parameter of type “array of T” or of function type T is adjusted to be of type “pointer to T”
最终结果是你的T A[S]
声明等同于T* A
,并且允许指向对象的指针,数组是对象,所以代码是有效的。