Search code examples
operator-overloadingada

How to Overload the Subscript/Subprogram Call Operator in Ada


We all know and love Ada.Containers.Vectors. Here's an example of its usage:

with Ada.Text_IO;
with Ada.Containers.Vectors;

procedure Example is
   use Ada.Text_IO;

   package Vectors_Integer is new Ada.Containers.Vectors (Natural, Integer);
   use Vectors_Integer;

   My_Vec : Vector := 1 & 2 & 3;
begin
   Put_Line (Integer'Image (My_Vec (0)));
end Example;

My question is simple: how does My_Vec (0) work, and how can I recreate this behavior in a type of my own?

I have been searching the internet for a while but I can't find to seem any explanation for how this expression works. The subscript operator, which uses the same syntax as the function call operator, cannot be overloaded using the normal syntax for operator overloading. I've read the package specification for Ada.Containers.Vectors, and there doesn't seem to be any explicit means through which Vector overloads this operator. I had guessed that the Element function might have something to do with it, but have been unable to use it to define a type of my own that replicates Vector's behavior. I'm at a complete loss on how to overload the subscript operator, even though it is clear that it is possible.


Solution

  • Expanding on the comments:

    As I note, the language defined generic package Ada.Containers.Vectors declares the private tagged type Vector in a way that leverages user-defined indexing. These operational aspects identify the subprograms needed to implement indexing at run-time. The corresponding functions are declared later in the specification. See also these usage fragments and these related examples.

    As @egilhh notes, the Rationale for Ada 2012 elaborates on this in regard to both user-defined indexing and iteration. Moreover, these operational aspects are not overloaded operators; for safety, the latter feature is limited to specific operators.

    As @Anh Vo notes, the Ada standard library uses hierarchical naming; using the fully qualified name helps eliminate ambiguity.

    Going forward:

    Ada is a programming language and an ISO standard. The reference manual (RM) is normative and the tag wiki cites the the various rationales that expand on changes to the language as it evolves. When perplexed by new features—which is often—I frequently start with the RM to get the terminology right and then go to the rationale(s), , et al. to see some examples.