boost::mpl::inherit_linearlyとLoki::Gen***Hierarchyの関係

  • Modern C++ Design Section 3.13をboost::mplで書ける
  • mpl::inherit_"linearly"は同書の"LinearHierarchy"を示しているのではないことに注意


#include <[]boost[]/mpl/inherit.hpp>
#include <[]boost[]/mpl/inherit_linearly.hpp>
#include <[]boost[]/mpl/assert.hpp>
#include <[]boost[]/mpl/vector.hpp>

namespace pst {
namespace date_2005_02_13 {
// Modern []C++[] Design Section 3.13
namespace mpl = []boost[]::mpl;
using mpl::_1; using mpl::_2;

typedef double window;
typedef int button;
typedef char scrollbar;
typedef mpl::vector< window, button, scrollbar > t_widgets;

// scattered version
template< typename T >
[]class[] event_handler {
public:
virtual void on_event(T& obj, int event_id) = 0;
virtual ~event_handler() { }
typedef event_handler type; // you []can[] omit
};

template< typename Sequence >
struct widget_event_handler_scattered
: mpl::inherit_linearly< Sequence, mpl::inherit2< _1, event_handler<_2> > >::type { };

[]class[] the_handler_scattered : public widget_event_handler_scattered<t_widgets> {
public:
virtual void on_event(window& w, int event_id) { }
virtual void on_event(button& b, int event_id) { }
virtual void on_event(scrollbar& s, int event_id) { }
};

// better version
template< typename T, typename Base >
[]class[] event_handler_linearly : public Base {
public:
virtual void on_event(T& obj, int event_id) = 0;
virtual ~event_handler_linearly() { }
typedef event_handler_linearly type; // you []can[] omit
};

// easier than inherit2, which represents "scatter"!
template< typename Sequence >
struct widget_event_handler_linearly
: mpl::inherit_linearly< Sequence, event_handler_linearly<_2, _1> >::type { };

[]class[] the_handler_linearly : public widget_event_handler_linearly<t_widgets> {
public:
virtual void on_event(window& w, int event_id) { }
virtual void on_event(button& b, int event_id) { }
virtual void on_event(scrollbar& s, int event_id) { }
};

// 4bytes * 3 > 4bytes * 1
BOOST_MPL_ASSERT_RELATION( sizeof(the_handler_scattered), >, sizeof(the_handler_linearly) );

} // date_2005_02_13
} // pst