You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ada中泛型包相似实例不兼容的解决方法及相关疑问

Ada泛型包类型冲突与标准库设计疑问

一、泛型包实例化后的类型冲突问题

我创建了一个名为Generic_Functions的泛型包,实例化方式与标准包Ada.Numerics.Generic_Real_Arrays类似,包规范如下:

with Ada.Numerics.Generic_Real_Arrays;

generic
    type Real is digits <>;
package Generic_Functions is

    package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real);
        use Real_Arrays;

    function Sphere_Function     (X : Real_Vector) return Real;
    --  function Ackley_Function     (X : Real_Vector) return Real;
    --  function Griewank_Function   (X : Real_Vector) return Real;
    --  function Rastrigin_Function  (X : Real_Vector) return Real;
    function Rosenbrock_Function (X : Real_Vector) return Real;

end Generic_Functions;

该包与标准包的区别在于,函数返回类型为Real而非Real'Base。

在主程序中同时使用该包与Ada.Numerics.Generic_Real_Arrays时,最初的实例化代码如下:

type Real is new Long_Float;

package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real);
    use Real_Arrays;

package Real_Functions is new Generic_Functions (Real);
    use Real_Functions;

随后尝试重命名Real_Functions中的函数:

function F (X : Real_Vector) return Real renames Rosenbrock_Function;

但编译器报错no visible subprogram matches the specification for "F"。

通过使用Real_Functions内部的Real_Arrays解决了该问题,修改后的代码:

type Real is new Long_Float;

package Real_Functions is new Generic_Functions (Real);
    use Real_Functions;
    use Real_Arrays;

我猜测问题源于use子句冲突,或是同一类型实例化的Generic_Real_Arrays被视为不同类型,但尝试显式指定重命名仍失败:

type Real is new Long_Float;

package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real);
    use Real_Arrays;

package Real_Functions is new Generic_Functions (Real);

function F (X : Real_Vector) return Real renames Real_Functions.Rosenbrock_Function;

我想到两种避免此类问题的方式:

  • 传递Generic_Real_Arrays实例中的Real和Real_Vector类型(尝试时无法使用其中的Real);
  • 传递实例本身(该思路来自Stack Overflow相关回答)。

想了解如何处理这类情况?若使用他人的包遇到该问题该如何解决?

二、Ada.Numerics.Generic_Real_Arrays返回Real'Base的原因与兼容性

请问Ada.Numerics.Generic_Real_Arrays中部分子程序返回Real'Base而非Real的原因是什么?为何这不会导致不兼容?


内容的提问来源于stack exchange,提问作者tymurmchyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 07:53:18