Bind或Lambda用于成员函数回调c ++ 14(Bind or Lambda for member function callback c++14)

编程入门 行业动态 更新时间:2024-10-27 21:17:34
Bind或Lambda用于成员函数回调c ++ 14(Bind or Lambda for member function callback c++14)

只是询问哪个是更新版本的c ++中更好的选择来处理成员函数的回调。 任何帮助将不胜感激,希望这个例子也会有所帮助。

template<class T> void addCallBack(void(T::*someFunc)(int), T* instance) { func = std::bind(someFunc, instance, _1); } std::function<void(int)> func ;

要么

template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } } std::function<void(int)> func;

Just inquiring which is a better choice in newer versions of c++ to handle callbacks of member functions. Any help would be much appreciated, hopefully the example will help also.

template<class T> void addCallBack(void(T::*someFunc)(int), T* instance) { func = std::bind(someFunc, instance, _1); } std::function<void(int)> func ;

or

template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } } std::function<void(int)> func;

最满意答案

这个:

template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } }

正在通过引用捕获参数instance ,这超出了addCallBack()末尾的范围,因此您最终会得到一个悬空引用。 所以,绝对不是那样的。

你想要做的是:

func = [instance](int x){ instance->someFunc(x); }

要不就:

func = [=](int x){ instance->someFunc(x); }

现在,在那之间不会出现功能差异

func = std::bind(&T::someFunc, instance, std::placeholders::_1);

但是lambda通常更容易阅读(就像在这种情况下一样),并且更容易内联,并且更能够执行任意复杂的事情。 后两者在这种情况下并不重要 - 但基本上总是喜欢lambdas是很好的理由。


当然,如果someFunc是一个重载名称,这someFunc ,这是另一个更喜欢lambda的理由 - 这将始终有效。

This:

template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } }

is capturing the argument instance by reference, which goes out of scope at the end of addCallBack() so you end up with a dangling reference. So, definitely not that.

What you want to do is:

func = [instance](int x){ instance->someFunc(x); }

or just:

func = [=](int x){ instance->someFunc(x); }

Now there isn't going to be a functional difference between that and:

func = std::bind(&T::someFunc, instance, std::placeholders::_1);

but the lambda is going to be typically easier to read (as it is in this case), and easier to inline, and is more capable of doing arbitrary complex things. The latter two don't matter in this case - but are good reasons to basically always prefer lambdas.


Of course, this doesn't work if someFunc is an overloaded name, which is one more reason to prefer a lambda - which will always work.

更多推荐

本文发布于:2023-08-02 18:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1380727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   函数   成员   Lambda   Bind

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!