What is a mixin, and why are they useful?

后端 未结 16 2024
無奈伤痛
無奈伤痛 2020-11-22 00:18

In \"Programming Python\", Mark Lutz mentions \"mixins\". I\'m from a C/C++/C# background and I have not heard the term before. What is a mixin?

Reading between the

16条回答
  •  有刺的猬
    2020-11-22 01:11

    OP mentioned that he/she never heard of mixin in C++, perhaps that is because they are called Curiously Recurring Template Pattern (CRTP) in C++. Also, @Ciro Santilli mentioned that mixin is implemented via abstract base class in C++. While abstract base class can be used to implement mixin, it is an overkill as the functionality of virtual function at run-time can be achieved using template at compile time without the overhead of virtual table lookup at run-time.

    The CRTP pattern is described in detail here

    I have converted the python example in @Ciro Santilli's answer into C++ using template class below:

        #include 
        #include 
    
        template 
        class ComparableMixin {
        public:
            bool operator !=(ComparableMixin &other) {
                return ~(*static_cast(this) == static_cast(other));
            }
            bool operator <(ComparableMixin &other) {
                return ((*(this) != other) && (*static_cast(this) <= static_cast(other)));
            }
            bool operator >(ComparableMixin &other) {
                return ~(*static_cast(this) <= static_cast(other));
            }
            bool operator >=(ComparableMixin &other) {
                return ((*static_cast(this) == static_cast(other)) || (*(this) > other));
            }
            protected:
                ComparableMixin() {}
        };
    
        class Integer: public ComparableMixin {
        public:
         Integer(int i) {
             this->i = i;
         }
         int i;
         bool operator <=(Integer &other) {
             return (this->i <= other.i);
         }
         bool operator ==(Integer &other) {
             return (this->i == other.i);
         }
        };
    
    int main() {
    
        Integer i(0) ;
        Integer j(1) ;
        //ComparableMixin c; // this will cause compilation error because constructor is protected.
        assert (i < j );
        assert (i != j);
        assert (j >  i);
        assert (j >= i);
    
        return 0;
    }
    

    EDIT: Added protected constructor in ComparableMixin so that it can only be inherited and not instantiated. Updated the example to show how protected constructor will cause compilation error when an object of ComparableMixin is created.

提交回复
热议问题