我有一个通用的包Containers.Stacks,看起来很像
generic
type Value_Type is private;
package Containers.Stacks with Preelaborate is
--Node stuff
type Stack is new Container with private;
--Other Stack stuff
--Private stuff
end Containers.Stacks;每件事似乎都很好。我想重用这个实现来创建一个扩展但更窄的用途堆栈。我想出了以下几点:
with Containers.Stacks;
generic
type Value_Type is range <>;
package Containers.Integer_Stacks with Preelaborate is
package Stacks is new Containers.Stacks(Value_Type);
use Stacks;
type Stack is new Stacks.Stack with null record;
procedure Add(Self : in out Stack);
procedure Subtract(Self : in out Stack);
--So on
end Containers.Integer_Stacks;重点是,我不想重新实现所有常见的堆栈,只为特定的整数堆栈。这是可行的,但留下了一个丑陋和奇怪的混乱的Containers.Integer_Stacks.Stack和Containers.Integer_Stacks.Stacks.Stack,我想避免。但是,尝试将包初始化放在私有部分也隐藏了所有的子例程。是否有更合适的方法来完成我正在尝试的工作,或者用户是否必须处理当前存在的同级程序包初始化?
替代方法:我发现可以定义一个名为Containers.Stacks的子包Containers.Stacks.Integer,如下所示:
generic
with function "+"(Left, Right: Value_type) return Value_Type is <>;
package Containers.Stacks.Integer is
procedure Add(Self : in out Stack);
end Containers.Stacks.Integer;而且这个很管用。但是现在我不能给Stack.Add打电话,我不得不给Add(Stack)打电话。
发布于 2017-03-14 22:21:00
由于各种原因,其他建议的答案都很好,但我认为,在兄弟姐妹中自动公开基本容器类型的子程序太重要了。因此,最好的答案是我最初的实施。希望其他开发人员会发现其他答案有帮助。
发布于 2017-03-12 18:44:29
你可以看看
with Containers.Stacks;
generic
type Value_Type is range <>;
with package Basis_Stack is new Containers.Stacks (Value_Type => Value_Type);
package Containers.Integer_Stacks with Preelaborate is
type Stack is new Basis_Stack.Stack with private;
...这确实要求用户自己适当地实例化Containers.Stacks。
发布于 2017-03-13 08:54:48
您对于解决方案的想法不是给您一个更窄的类型,而是使用更多的操作。
如果您想要一个更窄的类型(碰巧在内部使用现有类型),您可以这样做(未经测试的源代码):
private with Containers_Stack;
generic
type Value_Type is range <>;
package Containers.Integer_Stack
with Preelaborate
is
type Instance is tagged private with null record;
procedure Add (Item : in out Instance);
procedure Subtract (Item : in out Instance);
private
package Internal_Stack is new Containers.Stacks (Value_Type);
type Instance is tagged private with
record;
Data : Internal_Stack.Stack;
end record;
end Containers.Integer_Stack;这样,Containers.Integer_Stack的客户端只能精确地使用显式在包规范中列出的操作。
https://stackoverflow.com/questions/42746191
复制相似问题