3

在 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 的派生类就足够了,就像我在第一步中所做的那样。

4

1 回答 1

9

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

定义一个方法validate-superclass需要详细了解两个类元对象类中的每一个所遵循的内部协议。对于两个不同的类元对象类返回 true的方法validate-superclass声明它们是兼容的。

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

顺便说一句,我认为您可以定义一个更容易计算其实例的类

PS。在其他一些情况下,一些实现也会返回t

于 2013-10-18T12:42:46.940 回答