c++ - 如何制作一个typedef或用于指向类模板的方法指针?

标签 c++ c++11 std-function

我有一个从Parent子类化的对象,该对象创建了一个 child 。它为 child 提供了std::function来调用以报告状态,但是实际上std:function可能始终是父对象上的方法,因此,为了方便起见,提供了一个额外的构造函数,将其作为参数。
我已经创建了typedefstd::function,但是我不知道如何创建方法指针的typedef

class Child { // No Hungarian: abstract class, so no variables of this type exist.
  
public:

  typedef std::function< void( Child* child_in, Msg* pmsg ) > FuncCB;

  // can't figure out some way to define an MethodCB.
  //template<T> typedef void (T::*MethodCB)( Child* child_in, Msg* pmsg );

  Child( Parent* pparent_in, FuncCB asynccb_in ) :
      pparent( pparent_in ),
      asynccb_( asynccb_in )
  {
  };

  template<typename T>
  // can't figure out some way to define an MethodCB.
  //Child( Parent* pparent_in, MethodCB pmethod_in ) :
  Child( Parent* pparent_in, void (T::*pmethod_in)() ) :
      Child( pparent_in, [=]( Child* pchild, Msg* pmsg )
                         { (pparent_in->*pmethod_in)( pchild, pmsg ); } )
  {
  };

  // Either way, the callback is stored here:
  FuncCB funccb;


     :
     :
  // When child wants to send a message to parent.  Generally the parent
  // will have a method to take this call, but it could technically be
  // any other std::function object type as well.

  funccb( this, Msg( "blah" ) );

最佳答案

您的lambda不会接受任何参数,但是要匹配FuncCB的签名,它必须接受2个参数。修复您的lambda,您就可以开始了:

template <typename T>
using MemFunc = void (T::*) ();

using Func = std::function<void(Parent&, int msg)>;

template <typename T>
Child(T& parent, Func f)
{
    f(parent, 10);
}

template <typename T>
Child(T& parent, MemFunc<T> f) :
    Child(parent, [f](Parent& p, int msg) { (p.*f)(); }) // note that the lambda takes 2 arguments here, and we don't use parent, but p to call the member function!
{        
}
Example
正如molbdnilo指出的那样,如果T不同于Parent,则此方法将无效。为了使这项工作有效,您必须将父对象强制转换为您要传入的任何派生类型。但这要求您仅传递T类型的参数,否则将失败:
template <typename T>
Child(T& parent, MemFunc<T> f) :
    Child(parent, [f](Parent& p, int msg) { (dynamic_cast<T&>(p).*f)(); })
{        
}

关于c++ - 如何制作一个typedef或用于指向类模板的方法指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63682845/

相关文章:

c++11 - std::function,模板参数 T(X)

c++ - .cpp 文件中的虚拟 C++ 方法实现是否应该标记为虚拟?

main 中的 C++ 数组大小

c++ - QStackWidget 中的 QDockWidget

c++ - 高效实现二分查找

c++11 - std::将成员函数绑定(bind)到对象指针

c++ - 在 QPixmap 中写入文本

c++ - 如何将 C++11 std::stoi 与 gcc 一起使用?

c++ - 如何将非静态类成员 `std::bind` 转换为 Win32 回调函数 `WNDPROC`?

c++ - 将非静态成员函数作为 std::function 传递