boost::bind & boost::function pointers to overloaded or templated member functions

試著忘記壹切 提交于 2019-11-27 13:52:54

问题


I have a callback mechanism, the classes involved are:

class App
{
    void onEvent(const MyEvent& event);
    void onEvent(const MyOtherEvent& event);

    Connector connect;
}

class Connector
{  
   template <class T> void Subscribe(boost::function <void (const T&)> callback);
}

App::App()
{
    connect.Subscribe<MyEvent>(&App::OnEvent<MyEvent>);
}

First off this code doesn't compile, it's an illustration.

The use of templates complicates my example, but I left them in because its affecting my problem. It seems certain to me that my subscribe needs to be templated because the Connector class doesn't know how many event types it handles. When I try to create a:

boost::function f = &App::OnEvent, 

I tried creating OnEvent as a template function, with specializations, but it seems that the compiler is treating my OnEvent functions as overloads rather than template specializations, or else I get the template specialization not in namespace error if I try to explicitly declare it as

template <> OnEvent(const MyEvent& e) ...

I can get the following to compile:

boost::function <void (App*, const MyEvent&)> f = &App::OnEvent;
f(this, e); 

That compiles, runs, and works.

boost::function<void (const MyEvent&)> g = boost::bind(&App::OnEvent, this);

does not. I think its because I'm not correctly specifying the address of an overloaded function.

Having now explained all this to the teddy bear - I think that my question is "How do I correctly create a function pointer to an overloaded or templated member function and bind the this pointer to it?"


回答1:


I think you need to disambiguate the address of the overloaded function. You can do this by explicitly casting the function pointer to the one with the correct parameters.

boost::bind( static_cast<void (App::*)( MyEvent& )>(&App::OnEvent) , this, _1);

Similar problem + solution on gamedev.net




回答2:


You are going to want to do

boost::function<void (const MyEvent&)> g = boost::bind(&App::OnEvent, this, _1);

You should be able to do g(event); with that

I am not quite sure what you are trying to accomplish here, but that should solve one of your problems for now.



来源:https://stackoverflow.com/questions/1915880/boostbind-boostfunction-pointers-to-overloaded-or-templated-member-functio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!