问题描述
这个模板中const
关键字的作用是什么?
模板<class T, int const ROWNUM, int const COLNUM>类矩阵
这是否意味着这个模板只接受一个 const
作为参数?如果是这样,有没有办法将变量作为 COLNUM
和 ROWNUM
传递?
(当我尝试将变量作为模板的 COLNUM 传递时,它会给出错误:IntelliSense:表达式必须具有常量值")
忽略:
<块引用>[C++11: 14.1/4]:
非类型模板参数应具有以下之一(可选cv-qualified) 类型:
- 整数或枚举类型,
- 指向对象的指针或指向函数的指针,
- 对对象的左值引用或对函数的左值引用,
- 指向成员的指针,
std::nullptr_t
.
[C++11: 14.1/5]:
[ 注意: 其他类型在下面明确地或被管理 形式的规则隐含地禁止模板参数 (14.3).—结束注释 ] 在确定其类型时,模板参数上的顶级cv-qualifiers被忽略.
相同的措辞出现在 C++03 中的相同位置.
这部分是因为模板参数必须在编译时知道.因此,无论您是否有 const
,您可能不会传递一些变量值一个>:
模板<int N>无效 f(){N = 42;}模板<int const N>无效 g(){N = 42;}主函数(){f<0>();g<0>();静态常量 int h = 1;f<h>();g<h>();}
<块引用>
prog.cpp:在函数'void f() [with int N = 0]'中:
prog.cpp:15:从这里实例化
prog.cpp:4: 错误:需要左值作为赋值的左操作数
prog.cpp:在函数'void g() [with int N = 0]'中:
prog.cpp:16:从这里实例化
prog.cpp:10: 错误:需要左值作为赋值的左操作数
prog.cpp:在函数'void f() [with int N = 1]'中:
prog.cpp:19:从这里实例化
prog.cpp:4: 错误:需要左值作为赋值的左操作数
prog.cpp:在函数'void g() [with int N = 1]'中:
prog.cpp:20:从这里实例化
prog.cpp:10: 错误:需要左值作为赋值的左操作数
What is the effect of the const
keyword in this template?
template <class T, int const ROWNUM, int const COLNUM>
class Matrix
Does it mean that this template only accept a const
as parameter? If so, is there a way to pass a variable as the COLNUM
and ROWNUM
?
(when I try to pass a variable as the COLNUM for the template, it gives an error: "IntelliSense: expression must have a constant value")
It's ignored:
[C++11: 14.1/4]:
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- integral or enumeration type,
- pointer to object or pointer to function,
- lvalue reference to object or lvalue reference to function,
- pointer to member,
std::nullptr_t
.
[C++11: 14.1/5]:
[ Note: Other types are disallowed either explicitly below or implicitly by the rules governing the form of template-arguments (14.3). —end note ] The top-level cv-qualifiers on the template-parameter are ignored when determining its type.
The same wording is present at the same location in C++03.
This is partially because template arguments must be known at compile-time anyway. So, whether you have the const
there or not, you may not pass some variable value:
template <int N>
void f()
{
N = 42;
}
template <int const N>
void g()
{
N = 42;
}
int main()
{
f<0>();
g<0>();
static const int h = 1;
f<h>();
g<h>();
}
prog.cpp: In function ‘void f() [with int N = 0]’:
prog.cpp:15: instantiated from here
prog.cpp:4: error: lvalue required as left operand of assignment
prog.cpp: In function ‘void g() [with int N = 0]’:
prog.cpp:16: instantiated from here
prog.cpp:10: error: lvalue required as left operand of assignment
prog.cpp: In function ‘void f() [with int N = 1]’:
prog.cpp:19: instantiated from here
prog.cpp:4: error: lvalue required as left operand of assignment
prog.cpp: In function ‘void g() [with int N = 1]’:
prog.cpp:20: instantiated from here
prog.cpp:10: error: lvalue required as left operand of assignment
这篇关于模板参数中的 const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!