在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中,将计数类声明为标准类的衍生物就足够了,就像我在第一步中所做的那样。
答案 0 :(得分:8)
t
并添加:
在
validate-superclass
上定义方法需要详细的知识 两个类中的每个类的内部协议 元对象类。validate-superclass
上返回true的方法 对于两个不同类的metaobject类声明它们是 兼容。
你可以认为你的validate-superclass
是一个你明白自己在做什么的宣言。
顺便说一句,我认为您可以更轻松地定义a class which would count its instances。