I can create a variable-sized C-style array on the stack with no problems:
void f(int n) {
float data1[n]; // OK
}
But I can't do the same with std::array
:
void f(int n) {
std::array<float,n> data2; // error: ‘n’ is not a constant expression
}
The following example illustrates my point more thoroughly:
#include <array>
#include <cstdio>
template<int N>
class A{
public:
void print() {
printf("data[0]: %2.2f\n", data[0]);
}
private:
float data[N];
};
void f(int n) {
float data1[n]; // OK
std::array<float,n> data2; // error: ‘n’ is not a constant expression
A<n> data3; // error: ‘n’ is not a constant expression
}
int main(int argc, char **argv) {
f(3);
}
My Questions: Is there a way to create a variable-sized class/struct strictly on the stack? If so, how? If not, is this due simply to the specifications or is there an underlying technical reason that it is forbidden?