(defclass counting-class (standard-class) ((counter :initform 0))) # -6ren">
gpt4 book ai didi

common-lisp - sbcl/CLOS 为什么我必须在这里添加一个 "validate-superclass"-Method?

转载 作者:行者123 更新时间:2023-12-01 15:18:19 39 4
gpt4 key购买 nike

在 SBCL 中,当我定义新的元类时

CL-USER> (defclass counting-class (standard-class)
((counter :initform 0)))
#<STANDARD-CLASS COUNTING-CLASS>

并向 GF“make-instance”添加一个方法:

CL-USER> (defmethod make-instance :after ((class counting-class) &key)
(incf (slot-value class 'counter)))
#<STANDARD-METHOD MAKE-INSTANCE :AFTER (COUNTING-CLASS) {25302219}>

如果我尝试创建实例,则会收到错误消息:

CL-USER> (defclass counted-point () (x y) (:metaclass counting-class))

The class #<STANDARD-CLASS STANDARD-OBJECT> was specified as a
super-class of the class #<COUNTING-CLASS COUNTED-POINT>, but
the meta-classes #<STANDARD-CLASS STANDARD-CLASS> and
#<STANDARD-CLASS COUNTING-CLASS> are incompatible. Define a
method for SB-MOP:VALIDATE-SUPERCLASS to avoid this error.

现在,如果我添加所需的定义:

CL-USER>  (defmethod sb-mop:validate-superclass ((class counting-class)
(super standard-class))
t)
#<STANDARD-METHOD SB-MOP:VALIDATE-SUPERCLASS (COUNTING-CLASS STANDARD-CLASS) {26443EC9}>

有效:

CL-USER> (defclass counted-point () (x y) (:metaclass counting-class))
#<COUNTING-CLASS COUNTED-POINT>

我的问题是:为什么需要这样做?

从我的 POV 来看,将 count-class 声明为 standard-class 的派生类就足够了,就像我在第一步中所做的那样。

最佳答案

CLOS MOP validate-superclass 的规范表示默认方法仅在微不足道的情况下返回 t 并添加:

Defining a method on validate-superclass requires detailed knowledge of of the internal protocol followed by each of the two class metaobject classes. A method on validate-superclass which returns true for two different class metaobject classes declares that they are compatible.

您可以将您的 validate-superclass 视为您了解自己在做什么的声明。

顺便说一句,我想你可以定义 a class which would count its instances更容易。

PS。 Some implementations also return t in some other cases .

关于common-lisp - sbcl/CLOS 为什么我必须在这里添加一个 "validate-superclass"-Method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446174/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com