The RESHAPE()
intrinsic already works with arrays of arbitrary type, arbitrary kind, and arbitrary rank. As you note, it is difficult to write user functions that are that flexible, so at least with the current language features, it seems like using directly the intrinsic RESHAPE()
is the best approach.
There is another set of related gotchas that lurks in this swamp. The only way to allocate an array with nondefault bounds is with an explicit ALLOCATE() statement, so in these cases a simple assignment to the allocatable array is not sufficient, it takes at least two fortran statements. But further, even if the programmer allocates the target array with the right shape and bounds, the compiler is allowed to reallocate the lhs array within a simple array assignment statement with the default bounds. In order to avoid that, the assignment must be like the second assignment below.
allocate( array(lb1:ub1,lb2:ub2,lb3:ub3) )
array = reshape( vector, shape=shape(array) ) ! possible error, reallocation of lhs is allowed.
array(:,:,:) = reshape( vector, shape=shape(array) ) ! correct.
There are, of course, many ways to write that last statement to achieve the same result.
There are three possible changes to the language standard that would affect this predicament. First, the language standard could specify that reallocation cannot occur when the shapes of the lhs and rhs match; this change would require the above two assignments to always be exactly the same. The downside for this is that the ability to reallocate is sometimes a useful low-level optimization, one that would no long be allowed with that change. Second, if there were a way to change the bounds of an existing allocatable array (without a copy, just with metadata modifications), then this would not be an issue. The move_alloc()
intrinsic, which is the current way to transfer metadata between allocatable arrays, might be generalized to achieve this, but there are other ways it might be achieved too. Third, the reshape()
intinsic could be generalized to allow nondefault bounds. This solves this particular problem involving nondefault bounds, but it would not affect the other cases where the programmer needs to change the bounds of existing allocatable arrays.