简体   繁体   中英

lambda iso std::bind for member function

I have the following class on which I run clang-tidy.

template<typename Foo>
class Bar
{
public:

    template<class THandlerObj>
    Bar(void (THandlerObj::*pCmdHandler)(const Foo&), 
              THandlerObj* pCmdHandlerContext)          
        : m_cmdHandlerFunc(std::bind(pCmdHandler, pCmdHandlerContext, std::placeholders::_1))
       {
       }

private:
    std::function<void(const Foo&)> m_cmdHandlerFunc;
}

Clang is telling me that I should use a lambda function instead of std::bind. However I cannot get the syntax straight. I'm struggling with the fact that a member function is given which should be called on the context, but I don't see how to do that.

You can use lambda's capture list to capture member function pointer and object pointer and invoke them inside the lambda. Try this:

#include <functional>

template<typename Foo>
class Bar
{
public:

    template<class THandlerObj>
    Bar(void (THandlerObj::*pCmdHandler)(const Foo&), 
              THandlerObj* pCmdHandlerContext)          
        : m_cmdHandlerFunc(
            [=](const Foo& foo) { (pCmdHandlerContext->*pCmdHandler)(foo); })
        {
        }

private:
    std::function<void(const Foo&)> m_cmdHandlerFunc;
};

If your compiler supports C++20, you can also usestd::bind_front which is more lightweight and intuitive than std::bind .

template<class THandlerObj>
    Bar(void (THandlerObj::*pCmdHandler)(const Foo&), 
              THandlerObj* pCmdHandlerContext)          
        : m_cmdHandlerFunc(std::bind_front(pCmdHandler, pCmdHandlerContext))
        {
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM