Hi,
Just a note about the types being used: Prefer
std::size_t
rather than
int
here. For a couple of reasons:
1. You don't want negative values here;
2. I like to use exactly the same type as what a function or template expects: to avoid any unnecessary implicit casting. This is the definition from cppreference:
1 2 3 4 5
|
template<
class T,
std::size_t N
> struct array;
|
Btw, I managed to get the OP's code to work, but I had to resort to making
max_rank
global, and have it before any mention of the std::array. So this is clearly a bad solution, the use of the template is a much better idea.
I suppose the next question is: why the compiler has trouble with this ? It seems that the value is not "unknown", it was defined in main. My
guess is that the compiler generates an instance of the template the first time it sees it*, in this case whether that be for a function definition in the OP's code, or a forward declaration of the function. At this time the variable is unknown: it's scope is main. Making it
static
or
constexpr
in main doesn't help: the scope is still main.
* I know templates are instantiated only when they are needed, but here we have a function that uses one, so it is needed.