3

In SBCL, when I define new metaclass

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

and add a method to the 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}>

I receive an error, if I try to create an Instance:

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.

Now, if I add the required Definition:

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}>

It works:

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

My Question is: Why is this required?

From my POV it should be sufficient, to declare counting-class as an derivative of standard-class, as I did in the first step.

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
Patrick
  • 508
  • 2
  • 9

1 Answers1

9

CLOS MOP spec for validate-superclass says that the default method returns t only in trivial cases and adds:

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.

You could consider your validate-superclass to be a declaration that you understand what you are doing.

Incidentally, I think you can define a class which would count its instances easier.

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

sds
  • 58,617
  • 29
  • 161
  • 278
  • Thank you,sds! But could there be a more technical reason? CLISP, for example, does not need the additional method. – Patrick Oct 18 '13 at 22:34
  • the "technical reason" is in the spec: "... requires detailed knowledge of of the internal protocol ..." – sds Oct 19 '13 at 23:25
  • 2
    The point is to understand metaclasses, not to make a class to count instances. A counted-class is the first example of a metaclass given in AMOP. – Throw Away Account Jan 04 '20 at 02:26