I’m trying to overload the equality operator for a generic linked list class. Here’s the relevant code:
list.ads:
generic
type Element_Value_Type is private;
package List is
type List_Type is private;
type Element is private;
type Element_Ptr is private;
function "=" (L, R : List_Type) return Boolean;
-- Other linked list function declarations --
private
type Element is
record
Value : Element_Value_Type;
Next : Element_Ptr;
Prev : Element_Ptr;
end record;
type Element_Ptr is access Element;
type List_Type is
record
Length : Integer := 0;
Head : Element_Ptr := null;
Tail : Element_Ptr := null;
end record;
end List;
list.adb:
package body List is
function "=" (Left, Right : List_Type) return Boolean is
begin
-- Code for equality checking --
end "=";
-- Other function implementations --
end List;
main.adb:
with Text_IO;
with List;
use Ada;
procedure Main is
package Int_Lists is new List (Integer);
procedure Print_List (List : Int_Lists.List_Type) is
begin
-- code to print the contents of a list --
end
L1, L2 : Int_Lists.List_Type;
begin
Int_Lists.Append (L1, 1);
Int_Lists.Append (L2, 1);
Int_Lists.Append (L1, 2);
Int_Lists.Append (L2, 2);
Text_IO.Put_Line (Item => Boolean'Image (L1 = L2));
end Main;
And this is the error that I get in the last line of the body of Main:
operator for private type "List_Type" defined at list.ads:X, instance at line X is not directly visible
Is there any way to get it to see the “=” function? It works if I do Int_Lists."=" (L1, L2), or if I put use Int_Lists before the body of Main, but the first one sort of defeats the purpose of operator overloading and the second one allows unqualified access to all of the List functions from within Main.
Yes, you can use “=” with a private type generic parameter, however I would advise passing in the “=” function along with the private type but defaulting to the visible one, as the
with function … is <>indicates.Also, note that when comparing
Elementyou have to compare the value, not the entire record. (See the definition of “=” with Element parameters; it’s in the private section as one of Ada 2012’s expression functions.)Test_List.adsTest_List.adbtest.adbOutput is: