Search code examples
c++lambdastdbindclang-tidy

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.


Solution

  • 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 use std::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))
            {
            }