user15552120
user15552120

Reputation:

How to make generic formal parameter aliased

I am trying to declare a formal parameter like so:

generic
   S : aliased String;
package My_Package is
   Str : access constant String := S'Access;
end;

But this code does not compile. Why can't I make S aliased?

Upvotes: 2

Views: 185

Answers (2)

Simon Wright
Simon Wright

Reputation: 25491

ARM 12.4 (7) says

For a generic formal object of mode in, the actual shall be an expression. For a generic formal object of mode in out, the actual shall be a name that denotes a variable for which renaming is allowed (see 8.5.1).

and an expression can’t be aliased.

Even if you make S in out, you still can’t make it aliased.

You could say

generic
   S : String;
package My_Package is
   T : aliased String := S;
   Str : access constant String := T'Access;
end;

Upvotes: 2

Niklas Holsti
Niklas Holsti

Reputation: 2142

The simple answer is: because the Ada standard does not allow that. As for why it is not allowed, I do not know; I'm not aware of any discussion of the issue.

Why do you want to do that?

Your example code is of course incorrect in another way too: the initialization of Str should provide an access value, not a string value like S. But you cannot use S'Access since S is not aliased.

With GNAT, you can use S'Unrestricted_Access, even if the formal object is not aliased. If you do that, you should use the mode "in out" for the formal object; that will make it act like a renaming, more or less equivalent to pass-by-reference.

Upvotes: 3

Related Questions