【问题标题】:Boost C++. Passing a member function pointer with signature pointer to function提升 C++。将带有签名指针的成员函数指针传递给函数
【发布时间】:2014-05-28 14:54:27
【问题描述】:

这个问题可能有点混乱,但概念比较简单。

我有一个函数,它传递任何给定的非静态类方法和对象指针,并将它们绑定以产生一个简单的函数指针(参见下面的代码),

我有一个特定的签名(返回类型 void,一个 int 类型的参数),我希望方法是:

头文件:

//method_pointer.hpp
#include <boost/bind.hpp>
#include <boost/function.hpp>

class A
{
  public:
    void aMethod( int );
};


class B
{
  public:
    template < class T >
    B( boost::function< void ( int ) > method_ptr,
       T * obj_ptr )
    {
      bCallAMethod( boost::bind( method_ptr, obj_ptr, _1 ) );
    }

    void bCallAMethod( boost::function< void (int ) > );
};

源文件:

// method_pointer.cpp
#include <cstdio>

#include "method_pointer.hpp"

void A::aMethod( int x )
{
  printf("My number: %d\n", x);
}

void B::bCallAMethod( boost::function<void ( int ) > method_ptr )
{
  method_ptr( 5 );
}

int main( void )
{
  A a;
  B b( &A::aMethod, &a );
  return 1;
}

主代码实例化一个A类的对象;然后通过将 A 的方法和实例传递给构造函数来实例化 B 类的对象。然后 B 应该能够通过这个 boost::function 调用 A 中的方法。

如果我知道传入的是哪个方法(例如 &A::aMethod),我知道如何执行此操作,但目标是推广到具有该签名的任何方法。

我收到编译错误

$ g++ method_pointer.cpp -lboost_system -lrt
method_pointer.cpp: In function ‘int main()’:
method_pointer.cpp:18:11: error: invalid use of non-static member function ‘void A::aMethod(int)’

有什么想法吗?

如果可能的话,我也愿意保持一致并为类模板使用一些增强功能。

【问题讨论】:

    标签: c++ boost member


    【解决方案1】:

    您需要将B构造函数的原型更改为:

    template<typename T>
    B (void (T::*method_ptr)(int), T * obj_ptr)
    

    【讨论】:

    • 得到同样的错误 - 无效使用非静态成员函数。
    • Everything goes fine。如果您希望我们帮助您,您需要提供您的实际代码。
    猜你喜欢
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2018-08-25
    • 2021-11-29
    相关资源
    最近更新 更多