在Ada中,上下文可以确定“ +”不是字符串,而是整数运算符,如表达式:所示"+"(5,2)
。问题是,如何将该运算符存储在变量中?我想将该整数运算符或其他一些运算符作为接受两个Integer并返回Integer的二进制函数传递。在下面的代码中,我做了一个明确的函数,它仅调用运算符,可以将其用作解决方法。有什么方法可以避免使用该包装器,而直接传递(访问)Integer的“ +”运算符?
with Ada.Text_IO; use Ada.Text_IO; procedure operator is type binary_int_operator is access function(lhs : Integer; rhs : Integer) return Integer; --plus : binary_int_operator := Integer."+"'Access; --plus : binary_int_operator := Integer'Access("+"); --plus : binary_int_operator := Integer'"+"; --plus : binary_int_operator := "+"; function plus(lhs : Integer; rhs : Integer) return Integer is begin return lhs + rhs; end plus; begin Put_Line(Integer'Image("+"(5, 12))); end operator;
带注释的声明显示了我所做的一些尝试,但未编译。
恐怕你做不到。所述"+"
用于子程序Integer
在包被定义Standard
[ ARM A.1(17) ],并且因此固有[ AARM A.1(2.A) ]。不允许引用内部子程序[ ARM 3.10.2(32.3) ]。因此,编译程序
procedure Main is type Binary_Int_Operator is access function (lhs : Integer; rhs : Integer) return Integer; Plus : Binary_Int_Operator := Standard."+"'Access; begin null; end Main;
产量
6:34 prefix of "Access" attribute cannot be intrinsic
唯一的解决方法是使用间接寻址。该程序编译
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Main_Alt is type Operation is access function (Lhs, Rhs : Integer) return Integer; -- Sticking to "+" and "-" instead of names like Add or Subtract -- to demonstrate that you can reference operator subprograms -- (using the Access attribute) as long as they're not intrinsic. function "+" (Lhs, Rhs : Integer) return Integer is (Standard."+" (Lhs, Rhs)); function "-" (Lhs, Rhs : Integer) return Integer is (Standard."-" (Lhs, Rhs)); procedure Calc_And_Show (Lhs, Rhs : Integer; Op : Operation) is begin Put (Op (lhs, rhs)); New_Line; end Calc_And_Show; begin Calc_And_Show (5, 3, "+"'Access); Calc_And_Show (5, 3, "-"'Access); end Main_Alt;
和产量(如预期)
$ ./main_alt 8 2