我们的编程语言教授告诉我们:
“在 Ada 中,重载函数的返回类型可用于消除调用歧义(因此两个重载函数可以具有相同的参数)”
所以这意味着在 Ada 中,我们可以做这样的事情:
function Func (Var : Integer) return Integer;
function Func (Var : Integer) return Float;
然后创建这两个函数的不同实现,从而重载它们。
这对我来说没有多大意义,仅返回类型如何足以区分重载的子程序?当我们决定使用这些函数时,我们如何决定要调用它们中的哪一个?
我的教授有错吗?
你的教授是正确的。 Ada 能够使用您存储结果的位置作为调用函数版本的线索。例如,如果您将结果保存或传递到整数类型的变量中,它将调用整数版本。如果您将结果保存或传递到 Float 类型的变量中,它将调用 float 版本。参见示例:
with Ada.Text_IO; use Ada.Text_IO;
procedure jdoodle is
function Func (Var : Integer) return Integer is (Var*2);
function Func (Var : Integer) return Float is (Float(Var) * 4.0);
v1 : Integer := Func(2);
v2 : Float := Func(2);
begin
Put_Line(v1'Image);
Put_Line(v2'Image);
end jdoodle;
现在仍然有可能会遇到歧义的情况。例如,还存在以下过程:
procedure Print_Image(Value : Integer);
procedure Print_Image(Value : Float);
如果你尝试这样称呼他们:
procedure Print_Image(Func(2));
您会感到含糊不清,因为保存结果的位置有两个不同的选项,并且编译器没有任何线索知道选择哪个。不过,Ada 也有“限定表达式” 来帮助解决这个问题。考虑这个更新的例子:
with Ada.Text_IO; use Ada.Text_IO;
procedure jdoodle is
function Func (Var : Integer) return Integer is (Var*2);
function Func (Var : Integer) return Float is (Float(Var) * 4.0);
procedure Print_Image(Value : Integer) is
begin
Put_Line("Integer:" & Value'Image);
end Print_Image;
procedure Print_Image(Value : Float) is
begin
Put_Line("Float:" & Value'Image);
end Print_Image;
begin
-- Notice the Integer'() wrapped around the function call
-- This is a qualified expression that tells the compiler
-- which return type it expects. It is different from
-- a cast which transforms the value. A qualified expression
-- is a hint to the compiler. They use an apostrophe between
-- the type and the parenthesis
Print_Image(Integer'(Func(2)));
Print_Image(Float'(Func(2)));
end jdoodle;