jeudi 28 juin 2018

Is it good to implement mixin pattern using #include macro in C++

As we know, mixin is a design pattern to "insert" some behaviors to another class. For example, in Ruby, we can write code like this

module Flyable
  def fly
    puts "I'm flying";
  end
end

class Bird
  include Flyable
end

C++ does not have language level mixin support, but we can use multiple inheritance to insert code to derived class. But this solution still have it's own problems, like diamond inheritance, unable to override virtual method in interface, unable to access members from "sibling" modules etc.

Later I found I can use #include macro to insert code segment to class definition to achieve mixin:

// in Flyable.h
public:
void fly() {
    // do something ...
}
float flySpeed;

And in another file

// in Bird.h
class Bird {
#include "Flyable.h"
};

So all member variables and functions are inserted to Bird class.

This solution seems to have no obvious drawback. Codes are organized well into different files. Possible name conflicts can be avoided by carefully designed modules without overlapping functions/rules.

But still I afraid there're some problems I haven't seen yet. Is there any problems for this kind of mixin?

Aucun commentaire:

Enregistrer un commentaire