c++ - 模板与 Action 层次结构

标签 c++ templates

我正在创建一个按钮类,但很难在 2 种解决方案之间做出决定。

1) 模板化 Button 类,并让它在其构造函数中包含一个函数对象,以便在按下按钮时调用。与我一起编写代码的人担心这会导致代码膨胀/抖动。

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

我们也考虑过函数指针的使用,但还没有考虑透彻。

最佳答案

你可以使用 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();
   }
};

这样类很容易与函数指针、仿函数对象或类似boost::bind之类的东西一起使用:

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

struct SomeAction {
   void operator()() {}
};
Button b2 = Button(SomeAction());

关于c++ - 模板与 Action 层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2286207/

相关文章:

c++ - 输入第一个数组出了什么问题?

c++ - 模板是否应该为仅移动不同类型的参数创建非右值引用构造函数/赋值?

Angular 2 : Pass string to ngTemplateOutlet

c++ - 从模板函数返回的 const 相关名称,const 去哪里了?

c++ - Qt + iOS - AppDelegate 在哪里?

c++ - 如何检测何时按下特定键

c++ - 错误: aggregate ‘HMAC_CTX ctx’ has incomplete type and cannot be defined

c++ - 内联模板函数

c++ - 根据参数返回类型

C++模板替换错误