I want a static array in a template function, the length of which depends on the type with which the function specializes. My first attempt:
Title:
template<typename T> struct Length { const static size_t len; }; template<typename T> void func(){ static T vars[Length<T>::len];
Original file:
template<> const size_t Length<double>::len = 2; template<> const size_t Length<float>::len = 1;
However, g++ does not compile this and complains
error: storage size 'vars isnt constant
So what is the problem? I know that the size of a fixed-length array must be constant and known at compile time, but this seems to be the case here. When I write
const size_t len = 2; void func(){ static double vars[len]; }
It compiles without problems.
Question:
What is wrong with the code and what alternatives exist to achieve the desired behavior? I would not want to allocate memory at runtime ...
source share