【发布时间】:2020-01-21 04:03:17
【问题描述】:
我对 C++(14) 比较陌生。我正在努力通过阅读来自cpprefernce 的官方文档来增强我目前的知识。我对模板声明有一些疑问:This page 在类模板的声明中提供了以下可能的参数(非类型模板参数)。
type name(optional) // (1)
我的问题是:
1.)type name 是什么意思?我确定它与typename 提到的here 不同。
在同一个page 上,我看到了这个例子:
// simple non-type template parameter
template<int N>
struct S { int a[N]; };
但是从//1 来看,我看到类型名称是可选的,所以我假设下面的内容应该可以工作,但它没有:(事实上,我看到下面的声明template<N> 可以被视为具有类型参数的模板参数。) \
// simple non-type template parameter
template<N>
struct S { int a[N]; };
那么我对官方文档的理解/阅读哪里出了问题?
编辑:
我尝试了以下方法:
template< int>
struct S { int a[N]; };
编译时出现错误'N' was not declared in the scope。
【问题讨论】:
-
name 是可选的(
N),type 是必需的(int)。但在您的代码中,您实际上需要名称,因此您不能省略它。 -
你能举个例子吗,没有给出名字,只给出类型?我尝试在编辑中制作这样的示例,但也不起作用。
-
嗯,当然。它不起作用,因为您实际上需要名称。这有效:
template <int> struct S { }; -
对前向声明很有用。
template<int> struct S; -
顺便说一句 - cppreference 不是官方 文档集。不过它们非常有用。