消除对Boost ::的需求,以绑定我的功能

removing the need for boost::bind in my function

本文关键字:绑定 我的 功能 Boost 需求      更新时间:2023-10-16

这是一个中层问题。我通过存储指向功能的指针来注册我的活动。当前,我将功能存储在boost::function<void (Event*)>中,该功能应在启动事件时将事件指向事件作为参数。

要注册一个新事件,我要这样做..

Event::Register("click", "Image18", boost::bind(&MyMenu::OnClick, this, _1));
MyMenu::OnClick(DKEvent* event)  <-- calls this

我想尽可能简化代码的用户端。如何将boost :: bind方法推入事件类。我想减少注册活动,以下。少是好。

Event::Register("click", "Image18", &MyMenu::OnClick, this);

这可能涉及使用C 模板,因为所引用的类并不总是相同的。有人可以快速看一下我如何实现这一目标。

您可以将 Event::Register纳入模板函数,以成员函数和实例为参数:

//templated on the class and the return type and args of the member function
template <class T, typename Ret, typename... Args>
void Event::Register (std::string, std::string, Ret (T::*) (Args...), T*);

您甚至不需要在此处提供模板参数,编译器将为您推论。

您需要 variadic模板

template<typename... Args>
void Event::Register(std::string ID, Args... args)
{
   auto bind = std::bind(args...);
}

不需要boost::bind

您正在限制用户,并强迫他在实例上使用会员指针功能,而如果您允许它,则您将从多个来源中受益可以绑定到包括lambdas和自由功能的std::function,IMO您当前的表格比您想要实现的表单要好得多。

最好让您的班级用户选择他是否要将实例绑定到成员函数,您会通过提供多个模板过载(例如boost::binddivedive)来使界面复杂化。