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
is not required in your case
for instance, both classes Matrix_A
and Matrix_B
below are the same for the compiler point of view. const
here is just to enforce the fact that ROWNUM
and COLNUM
are constant for humans point of view, but not required.
template <class T, int const ROWNUM, int const COLNUM>
class Matrix_A
{
};
template <class T, int ROWNUM, int COLNUM>
class Matrix_B
{
};
Moreover following class Matrix_C
also specify similar constant variables ROWNUM
and COLNUM
in another way:
template <class T>
class Matrix_C
{
static int const ROWNUM = 5;
static int const COLNUM = 20;
};
// the following three objects use constant variables ROWNUM and COLNUM
Matrix_A<bool,5,20> a;
Matrix_B<bool,5,20> b;
Matrix_C<bool> c;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With