我对C++(14)比较陌生。我正在努力通过阅读cpprefernce的官方文档来增强我目前的知识。我有一些关于模板声明的问题:This页面在类模板的声明中提供了以下可能的参数(非类型模板参数)。
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。
发布于 2020-01-21 13:00:10
要实现这一点,N必须是一个类型。
模板只接受后跟该类型的可选名称的类型。例如,这个可能会工作(尽管我还没有尝试过):
template <int> // ...但请注意,N并未声明。如果你想在模板中使用N,你需要像这样声明N:
template <int N> // ...在这里,N被声明为int,因此您可以像使用int一样使用它。
注意:您还可以选择以下内容:
template <class N> // ...在这里,N成为了一个类型的模板替代品。它不是上面提到的int类型。
当然,这可能不是您想要的。
https://stackoverflow.com/questions/59834020
复制相似问题