模板与动作层次结构

Per*_*son 0 c++ templates

我正在创建一个按钮类,我很难决定两种解决方案.

1)对Button类进行模板化,并在按下按钮时使用其构造函数中的函数对象进行调用.我正在编码的那个人担心这会导致代码膨胀/颠簸.

2)创建一个ButtonAction基类,每个按钮都有一个不同的ButtonAction.因此,Button当按下按钮时,类在其构造函数中采用ButtonAction进行调用.

我们也考虑过使用函数指针,但没有仔细考虑过.

sth*_*sth 5

您可以使用boost::function<>对象进行操作.这样您就不需要任何模板,按钮类变得非常灵活:

struct Button {
   typedef boost::function<void ()> action_t;
   action_t action;

   Button(const action_t &a_action) : action(a_action) {
   }

   void click() {
      action();
   }
};
Run Code Online (Sandbox Code Playgroud)

这样,类很容易使用函数指针,仿函数对象或boost :: bind之类的东西:

void dosomething();
Button b1 = Button(&dosomething);

struct SomeAction {
   void operator()() {}
};
Button b2 = Button(SomeAction());
Run Code Online (Sandbox Code Playgroud)