1

我正在尝试根据以下接口在 Ada 中对一组解析器进行建模:

package Parsers is

   type Parser is interface;
   type DataArray is array(Integer range <>) of String(1..100);

   function Parse(Object : access Parser; FilePath : String) return DataArray is abstract;

end Parsers;

第一个 Parser 接口成员是一个文本解析器,如下所示:

with Parsers;

package TextParsers is
   type Parser is new Parsers.Parser with null record;

   overriding function Parse(Object : access Parser; FilePath : String) return Parsers.DataArray;
   end TextParsers;                                       

with Parsers;
use Parsers;

package body TextParsers is

   overriding function Parse(Object : access Parser; FilePath : String) return Parsers.DataArray is
      Data : Parsers.DataArray (0..144);
   begin
      -- just stubbed out
      return Data;
   end Parse;
end TextParsers;

最后,我希望有一个工厂方法根据提供的路径创建这些解析器,比如检测它是 txt 文件还是 csv 等。这是工厂代码:

with Parsers;
use Parsers;

package ParserFactories is
   function GetParser(Path : String) return Parsers.Parser;
end ParserFactories;


with Parsers, TextParsers;

package body ParserFactories is
   function  GetParser(Path : String) return Parsers.Parser is
      Text : TextParsers.Parser;
      Parse : Parsers.Parser'Class := Text;
   begin
      return Parse;
   end GetParser;
end ParserFactories;

我不断收到“不允许动态标记的表达式”编译器错误,我无法弄清楚如何创建这些实现 Parser 接口的对象并将其从该函数中返回。有没有办法在 Ada 中做到这一点?

4

2 回答 2

2

您正在尝试返回一个Parsers.Parser类型。这是不允许的(也不是您打算做的)。改为Parsers.Parser'Class改为。

于 2012-07-23T08:11:52.633 回答
1

答案是您不返回接口的类型,而是返回对象的类型……否则您可以返回接口的类以指示您要将其分配给该抽象类型的变量。

Procedure Testing is

package Interface_Test is
    Type IBob is interface;
    Function Make Return IBob is abstract;
    Function Image( Object : In IBob ) Return String is abstract;

    Generic
        Type Data is (<>);
        Default_Data : In Data;
    Package Container is
        Type Data_Container is NEW IBob with private;
    private
        Type Data_Container is new IBob with record
        Info  : Data:= Default_Data;
        end record;

        Overriding Function Make Return Data_Container;
        Overriding Function Image(Object : In Data_Container) Return String;
    end Container;
end Interface_Test;

package Body Interface_Test is
    Package Body Container is

        Function Make Return Data_Container is
        begin
        Return Result : Data_Container;
        end Make;

        Function Image( Object : Data_Container ) Return String is 
        begin
        return Data'Image( Object.Info );
        end image;

    end Container;
end Interface_Test;


package J is new Interface_Test.Container( Integer, 1 );
use type J.Data_Container;
Test : J.Data_Container:= J.Make;

Use Ada.Text_IO;

Begin
  put_line( Test.Image );
End;
于 2012-08-10T17:16:45.740 回答