1

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.

Frank
  • 2,446
  • 7
  • 33
  • 67
  • Is there a particular reason that "clang-tidy" doesn't like `bind`? Seems like how you're using it is correct to me, but that's just reading it, not running it through that command. Maybe post the entire error message instead of just your summary? – Kevin Anderson Oct 19 '21 at 15:05
  • @KevinAnderson I quote from the clang docs: "std::bind can be hard to read and can result in larger object files and binaries due to type information that will not be produced by equivalent lambdas." – Frank Oct 19 '21 at 15:13

1 Answers1

3

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))
        {
        }
康桓瑋
  • 33,481
  • 5
  • 40
  • 90