在C ++中指定成员函数作为回调11 [英] Specifying a member function as a callback in C++11
问题描述
我有以下:
typedef std::function<bool (const std::string&)> SomethingCoolCb;
class ClassA
{
public:
void OnSomethingCool(const SomethingCoolCb& cb)
{
_cb = cb;
}
private:
SomethingCoolCb _cb;
};
class ClassB
{
public:
ClassB();
bool Juggle(const std::string& arg);
private:
ClassA _obj;
};
,我想指定ClassB :: Juggle()成员函数作为ClassB :: _obj。在C ++ 11中正确的方法是(在ClassB的构造函数中):
and I want to specify the ClassB::Juggle() member function as the callback to ClassB::_obj. Would the proper way to do that in C++11 be (in ClassB's constructor):
ClassB::ClassB()
{
_obj.OnDoSomethingCool(
[&](const std::string& arg) -> bool
{
return Juggle(arg);
});
}
根据我的理解,编译器会将std :: function对象的上述lambda代码。所以当回调被调用时,它将调用std :: function :: operator()成员,然后它将调用ClassB :: Juggle(),而不是直接调用ClassB :: Juggle()。除非我错误地看到在封面下发生了什么,这似乎是一个低效率。是否有更好的方法?
From what I understand, the compiler will make a std::function object out of the above lambda code. So when the callback gets invoked, it'll call the std::function::operator() member and then it'll invoke ClassB::Juggle() instead of invoking ClassB::Juggle() directly. Unless I'm mistaken about what happens under the covers, that all seems to be a little inefficient. Is there a better way?
推荐答案
只使用 std :: function
如果你真的需要多态性函数。
Only use std::function
if you really need polymorphic functions. Otherwise make it a template.
要使成员函数适用于函数,请使用 std :: mem_fn
code> bind 一个对象的第一个参数,结果函子可以作为你的回调。
To adapt a member function to a functor use std::mem_fn
and then bind
an object to the first argument, the resulting functor can serve as your callback.
范例:
#include <string>
#include <functional>
template<typename F>
class ClassA
{
public:
ClassA(F f) : _cb(f) {}
private:
F _cb;
};
class ClassB
{
public:
ClassB()
: _obj(std::bind(&ClassB::Juggle, this,
std::placeholders::_1))
{}
bool Juggle(const std::string& arg) {return true;}
private:
ClassA<decltype(std::bind(
std::declval<bool (ClassB::*)(const std::string&)>()
, std::declval<ClassB*>()
, std::placeholders::_1
) ) > _obj;
};
int main()
{
ClassB b;
return 0;
}
这样做是以可怕的丑陋为代价的。
This side-steps the cost of function at the cost of being horribly ugly.
这篇关于在C ++中指定成员函数作为回调11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!