Ada容器向量Update_Element使用报错:元素更新问题求助
修复Ada向量Update_Element使用问题
错误原因分析
- 赋值给in模式参数:
TestUpdate函数中n是默认的in模式参数,属于只读属性,直接给n.Size赋值违反Ada参数访问规则。 - Access属性传参错误:
TestUpdate'Access(5)写法非法,'Access仅用于获取子程序地址,不能直接绑定参数。
修复方案
方案1:嵌套子程序捕获参数
通过嵌套子程序封装需要传递的额外参数,适配Update_Element要求的回调类型:
with Ada.Containers.Vectors; procedure Test_Update is type Node is record Parent : Integer := -1; Size : Integer := -1; end record; package NodeVector is new Ada.Containers.Vectors ( Index_Type => Natural, Element_Type => Node ); Nodes : NodeVector.vector; Current_Node : Node; begin Current_Node.Size := 10; Nodes.Append(Current_Node); -- 嵌套子程序捕获要添加的值 declare Add_Value : constant Integer := 5; function Update_Node(Element : in Node) return Node is Updated : Node := Element; -- 复制原元素 begin Updated.Size := Updated.Size + Add_Value; return Updated; end Update_Node; begin NodeVector.Update_Element(Nodes, 0, Update_Node'Access); end; end Test_Update;
方案2:Ada 2012+匿名子程序简化写法
如果使用Ada 2012或更高版本,可直接用匿名子程序省略嵌套块:
with Ada.Containers.Vectors; procedure Test_Update is type Node is record Parent : Integer := -1; Size : Integer := -1; end record; package NodeVector is new Ada.Containers.Vectors ( Index_Type => Natural, Element_Type => Node ); Nodes : NodeVector.vector; Current_Node : Node; begin Current_Node.Size := 10; Nodes.Append(Current_Node); NodeVector.Update_Element(Nodes, 0, function (Element : in Node) return Node is Updated : Node := Element; begin Updated.Size := Updated.Size + 5; return Updated; end'Access); end Test_Update;
关键说明
Update_Element要求的回调必须是接受单个in元素参数、返回同类型元素的函数,或接受in out元素参数的过程。- 不能直接给回调传递额外参数,需通过嵌套/匿名子程序捕获外部变量实现参数传递。
- 所有对元素的修改必须基于原元素的副本(
in参数只读),修改后返回新元素完成更新。
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

