I was working on a template function with non-type parameters (to avoid dynamic allocation of arrays) when a number of questions arose. My first question regards compile-time variable assignment. This arose from the following attempts at calls to the template function:
template<int n>
int *getDegrees(int A[][n]) {
//return degrees
}
int main(int argc, char **argv) {
int n = 10;
int A[n][n];
int *degs = getDegrees<n>(A);
}
Here, we have two errors: first, the compiler is unable to resolve the call to getDegrees(A)
:
main.cc:27: error: no matching function for call to ‘getDegrees(int [(((long unsigned int)(((long int)n) + -0x00000000000000001)) + 1)][(((long unsigned int)(((long int)n) + -0x00000000000000001)) + 1)])’
Second, we're unable to use n
in the template call as it isn't a constant expression. Simply making n
constant does resolve the issues
const int n = 10;
however, if I were to do
int m = 10;
const int n = m;
we get the same errors. While the second assignment may be allowed by the compiler, is it considered bad form to do so? Additionally, why would making n
constant make a difference in resolving the function call?
My other question regards vlas: is memory allocated for them on the stack or the heap (and is this compiler-dependent)? There appears to have been some controversy in even allowing them in C++, should they be avoided in favor of vectors (or similar containers)?
Appreciate any insight!