函数模板的模板参数名是否可以在函数参数列表中多次使用?
Can a template parameter name of a function template be used more than once in the function parameter list?
我制作了这个函数,专门用于二次型二维数组:rowLength == colLength
如果传递矩形数组,函数将失败,因为实现不适合矩形:rowLength != colLength
只使用一个模板确保数组是二次的。让编译器警告您不要使用矩形,因为参数必须等于 "satisfy" 模板系统。
我知道会有不同的解决方案,但这个解决方案完全符合我的意愿。
template <std::size_t sideLength>
void functionForQuadraticArrayOnly( const int( &arr )[ sideLength ][ sideLength ] )
{// body....}
问题:
这个模板的使用是否正确?是未定义行为还是其他原因?
你在这里做的事是安全的。但是,最好了解标准中提到的一种特殊情况。
考虑以下示例:
typedef int N;
template<N X, typename N, template<N Y> class T> struct A;
这里,X
是int
类型的非类型模板参数,Y
是与[的第二个模板参数相同类型的非类型模板参数=14=].
请注意 Y
是 而不是 类型 int
的非类型模板参数,因为模板参数 N
隐藏了 N
的 typedef
。
这是根据 [basic.scope.temp]/4]
规定的:
The declarative region of the name of a template parameter is nested within the immediately-enclosing declarative region. [ Note: As a result, a template-parameter hides any entity with the same name in an enclosing scope]
我制作了这个函数,专门用于二次型二维数组:rowLength == colLength
如果传递矩形数组,函数将失败,因为实现不适合矩形:rowLength != colLength
只使用一个模板确保数组是二次的。让编译器警告您不要使用矩形,因为参数必须等于 "satisfy" 模板系统。
我知道会有不同的解决方案,但这个解决方案完全符合我的意愿。
template <std::size_t sideLength>
void functionForQuadraticArrayOnly( const int( &arr )[ sideLength ][ sideLength ] )
{// body....}
问题: 这个模板的使用是否正确?是未定义行为还是其他原因?
你在这里做的事是安全的。但是,最好了解标准中提到的一种特殊情况。
考虑以下示例:
typedef int N;
template<N X, typename N, template<N Y> class T> struct A;
这里,X
是int
类型的非类型模板参数,Y
是与[的第二个模板参数相同类型的非类型模板参数=14=].
请注意 Y
是 而不是 类型 int
的非类型模板参数,因为模板参数 N
隐藏了 N
的 typedef
。
这是根据 [basic.scope.temp]/4]
规定的:
The declarative region of the name of a template parameter is nested within the immediately-enclosing declarative region. [ Note: As a result, a template-parameter hides any entity with the same name in an enclosing scope]