Patrick Kelly
Patrick Kelly

Reputation: 603

Hiding certain operators in Ada

Say I have the following type:

type Example_Type is new Float;

A large number of intrinsic operators will be defined for Example_Type, which is good in the overwhelming majority of cases. Like:

function "+"(Left, Right : Example_Type) return Example_Type;

and

function "*"(Left, Right : Example_Type) return Example_Type;

But let's say multiplication of two Example_Type's shouldn't equal another Example_Type, like what occurs with Dimensions. How can these intrinsic operators be hidden selectively?

Upvotes: 1

Views: 102

Answers (3)

Jeffrey R. Carter
Jeffrey R. Carter

Reputation: 3358

You can override them to be abstract, but I think this is the wrong approach. Rather than trying to get rid of operations, it's usually better to declare the type to only have the operations needed:

type Example is private;

function "+" (Left : Example; Right : Example) return Example;
-- "*" not defined

The problem with this for types that are otherwise numeric is that you can't use numeric literals with the type. This can be somewhat alleviated by things like

function "+" (Right : Integer) return Example;

so that you write +42 rather than 42, which isn't too bad, though it's still awkward in the presence of a binary operator: X / (+42).

Upvotes: 2

Jim Rogers
Jim Rogers

Reputation: 5021

You must define an overloaded function which produces a result of the type you want. While it is sometimes desirable to disable an intrinsic operator definition, it is not necessary to do so to get the operator definition you want.

type Example_Type is new float;
type Other_Type is new float;

function "*" (Left, Right : Example_Type) return Other_Type;

Ada can resolve the overloading based upon the return type of the function.

Upvotes: -1

Jacob Sparre Andersen
Jacob Sparre Andersen

Reputation: 6601

You make the disallowed operations abstract:

procedure Disallow is
   type Length is digits 10;
   function "*" (Left, Right : Length) return Length is abstract;

   A, B, C, D : Length := 2.0;
begin
   C := A + B;
   D := A * C; --  Compiler will complain here.
end Disallow;

Upvotes: 6

Related Questions