在Ada中返回有限类型

时间:2013-10-14 22:58:11

标签: ada

我试图通过构造函数返回有限类型。我理解,因为它是一种有限的类型,我无法复制类型,但我不确定最好的方法。我使用扩展的返回语句工作,但有人告诉我,如果没有它,我应该能够返回有限的类型。

thing_protected.ads:

package Thing_Protected is

   type Thing is protected interface;
   procedure Verb_It (Object : in out Thing; Key : String) is abstract;

   function Create return Thing'Class;

private

   protected type Thing_Impl is new Thing with
      overriding procedure Verb_It (Key : String);
   private
      Data : Integer;
   end Thing_Impl;

end Thing_Protected;

thing_protected.adb:

package body Thing_Protected is

   function Create return Thing'Class is
   begin

        -- Not sure how to make this work:
        -- return Thing_Impl'(Data=><>, others=><>);
        --  thing_protected.adb:6:35: expected type "Thing_Impl" defined at thing_protected.ads:10
        --  thing_protected.adb:6:35: found a composite type

        -- extended return:
        --  return X : Thing_Impl do
        --      null;
        --  end return;

        -- shortened version:
        return X : Thing_Impl;
   end;

  protected body Thing_Impl  is
      overriding procedure Verb_It (Key : String) is
      begin
        null;
      end;
   end Thing_Impl;

end Thing_Protected;

main.adb:

with Thing_Protected;

procedure Main is
   Thing_Instance : Thing_Protected.Thing'Class := Thing_Protected.Create;
begin
    null;
end;

1 个答案:

答案 0 :(得分:1)

嗯,所以你想初始化数据?你可以使用泛型/包来做到这一点......它有点长,也许有点复杂。

package Thing_Protected is

type Thing is protected interface;

procedure Verb_It (Object : in out Thing; Key : String) is abstract;

function Create return Thing'Class;

private

generic
    Default : in Integer;
package Implementation is
    protected type Thing_Impl is new Thing with
    procedure Verb_It (Key : String);
    private
    Data : Integer:= Default;
    end Thing_Impl;

    Function Create return Thing'Class;
end Implementation;

end Thing_Protected;

package body Thing_Protected is

package body Implementation is
    protected body Thing_Impl  is
    overriding procedure Verb_It (Key : String) is
    begin
        null;
    end;
    end Thing_Impl;

    function  Create return Thing'class is
    begin
    return Result : Thing_Impl do
        null;
    end return;
    end Create;
end Implementation;


function K( Data_Val : Integer := 10 ) return Thing'Class is
    Package I is new Implementation( Default => Data_Val );
begin
    return X : Thing'Class := I.Create do
    null;
    end return;
end K;


function Create return Thing'Class is ( K );

end Thing_Protected;