我正在尝试创建一些终端日志记录颜色,以便能够更清楚地看到我的错误。这样做对我来说似乎很明显,我必须创建如下的常量。因为我不想每次调用常量时都创建一个实例,所以对我来说像这样做是有意义的,但是编译器似乎与我的概念不同……A once function has generic or anchored result
什么是anchored
结果?
由于编译器始终是硬道理,而我则是最重要的人,为什么我错了,他是对的吗?
class
TERMINAL_COLOR
create
make
feature -- Initialization
make (a_fg: like foreground; a_bg: like background)
do
foregound := a_fg
background := a_bg
end
feature -- Status report
foreground: INTEGER
background: INTEGER
feature -- Colors
Black: like Current
once -- compiler doesn't agree with me
create Result.make (30, 40)
ensure
instance_free: class
end
end
最佳答案
anchor 类型是当您使用“喜欢功能”(注意,您也可以使用“喜欢{FOO} .bar”)。
另外,不要忘记一次是“每堂课一次”(不是按类型)。
因此,一次函数的结果类型不能使用任何形式的泛型。
例如
class FOO [G]
feature
bar: STRING
once
Result := generating_type
end
end
(create {FOO [INTEGER]}).bar
将返回与(create {FOO [STRING]}).bar
相同的对象。因此,现在,如果
bar
将在类FOO中返回G
,则会引起麻烦,因为无法返回符合任何形式(INTEGER,STRING等)的值。这就是为什么一次结果类型禁止泛型的原因。
相同的逻辑适用于 anchor 类型(例如
like feature_name
),因为feature_name
可以与其他类型的后代一起重新定义。
关于compiler-errors - Eiffel : once function has generic or anchored result. Trying to create constants,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52857596/