转换的std ::绑定为一个函数指针(convert std::bind to function p

2019-06-18 20:38发布

我有一个有需要一个函数指针作为第一个参数的方法的第三方库:

int third_party_method(void (*func)(double*, double*, int, int, double*), ...);

我想一个指针传递给被如下声明一个类的方法:

class TestClass
{
    public:
        void myFunction (double*, double*, int, int, void*);

我试图通过这一功能如下:

TestClass* tc = new TestClass();
using namespace std::placeholders;
third_party_method(std::bind(&TestClass::myFunction, tc, _1, _2, _3, _4, _5), ...);

然而,这并不编译:

Conversion of parameter 1 from 'std::tr1::_Bind<_Result_type,_Ret,_BindN>' to 'void (__cdecl *)(double *,double *,int,int,void *)' is not possible
with
[
    _Result_type=void,
    _Ret=void,
    _BindN=std::tr1::_Bind6<std::tr1::_Callable_pmf<void (__thiscall TestClass::* const )(double *,double *,int,int,void *),TestClass,false>,TestClass *,std::tr1::_Ph<1>,std::tr1::_Ph<2>,std::tr1::_Ph<3>,std::tr1::_Ph<4>,std::tr1::_Ph<5>>
]

有没有什么办法可以通过成员函数?

Answer 1:

有没有什么办法可以通过成员函数?

除非你的类对象是某种全局对象的 - 这是不可能的。 因为对象可能包含一些数据,而函数指针刚刚指向功能 - 它不包含任何运行时环境,只有编译时一个。

如果您接受具有每个回调经过编译时唯一的ID,那么你可以用下面的方法概括。

用法:

void test(void (*fptr)())
{
    fptr();
}

struct SomeStruct
{
    int data;
    void some_method()
    {
        cout << data << endl;
    }
    void another_method()
    {
        cout << -data << endl;
    }
};

int main()
{
    SomeStruct local[] = { {11}, {22}, {33} };

    test(get_wrapper<0>(  boost::bind(&SomeStruct::some_method,local[0]) ));
    test(get_wrapper<1>(  boost::bind(&SomeStruct::another_method,local[0]) ));

    test(get_wrapper<2>(  boost::bind(&SomeStruct::some_method,local[1]) ));
    test(get_wrapper<3>(  boost::bind(&SomeStruct::another_method,local[1]) ));

    test(get_wrapper<4>(  boost::bind(&SomeStruct::some_method,local[2]) ));
    test(get_wrapper<5>(  boost::bind(&SomeStruct::another_method,local[2]) ));
}

它可能不需要唯一ID对每个调用,例如因为函子可能已经有不同的类型,或者它们的使用范围运行时间不重叠。 但是,使用更安全,唯一的ID各一次。

执行:

现场演示

#include <boost/optional.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <ostream>
using namespace std;

template<unsigned ID,typename Functor>
boost::optional<Functor> &get_local()
{
    static boost::optional<Functor> local;
    return local;
}

template<unsigned ID,typename Functor>
typename Functor::result_type wrapper()
{
    return get_local<ID,Functor>().get()();
}

template<typename ReturnType>
struct Func
{
    typedef ReturnType (*type)();
};

template<unsigned ID,typename Functor>
typename Func<typename Functor::result_type>::type get_wrapper(Functor f)
{
    (get_local<ID,Functor>()) = f;
    return wrapper<ID,Functor>;
}

// ----------------------------------------------------------------------

void test(void (*fptr)())
{
    fptr();
}

struct SomeStruct
{
    int data;
    void some_method()
    {
        cout << data << endl;
    }
    void another_method()
    {
        cout << -data << endl;
    }
};

int main()
{
    SomeStruct local[] = { {11}, {22}, {33} };

    test(get_wrapper<0>(  boost::bind(&SomeStruct::some_method,local[0]) ));
    test(get_wrapper<1>(  boost::bind(&SomeStruct::another_method,local[0]) ));

    test(get_wrapper<2>(  boost::bind(&SomeStruct::some_method,local[1]) ));
    test(get_wrapper<3>(  boost::bind(&SomeStruct::another_method,local[1]) ));

    test(get_wrapper<4>(  boost::bind(&SomeStruct::some_method,local[2]) ));
    test(get_wrapper<5>(  boost::bind(&SomeStruct::another_method,local[2]) ));
}

多线程访问PS Beaware -在这种情况下,你应该使用某种类型的线程本地存储的数据。



Answer 2:

它不会编译,因为第三方函数需要一个指针到函数,但是你想传递一个指针-TO- 成员 -功能。 这两种类型是根本不同的 ,不能互换。 事实上,指针到成员函数通常是非常奇怪的动物 。

下面是一个SSCCE说明您遇到的问题:

#include <iostream>
#include <iomanip>
using namespace std;

typedef void(*SpeakFn)(void);

void Bark()
{
    cout << "WOOF" << endl;
}

void Meow()
{
    cout << "meeow" << endl;
}

void SpeakUsing(SpeakFn fn)
{
    fn();
}

class Alligator
{
public:
    void Speak()
    {
        cout << "YAWWW" << endl;
    }
    typedef void(Alligator::*AlligatorSpeakFn)(void);

    void SpeakUsing(AlligatorSpeakFn fn)
    {
        (this->*fn)();
    }
};

int main()
{
    SpeakUsing(&Bark); // OK

    Alligator a;
    Alligator::AlligatorSpeakFn mem_fn = &Alligator::Speak;
    a.SpeakUsing(mem_fn);   // OK

    SpeakUsing(mem_fn); // NOT OK -- can't cvt from fn-ptr to mem-fn-ptr
}

你可以不叫SpeakUsing ,因为它无法转换为指针到函数指针到成员函数。

使用静态成员函数来代替,如:

class Alligator
{
public:
    static void Speak()
    {
        cout << "YAWWW" << endl;
    }
    typedef void(*AlligatorSpeakFn)(void);

    void SpeakUsing(AlligatorSpeakFn fn)
    {
        fn();
    }
};


Answer 3:

正如其他人提到你没有选择,只能使用全局或静态数据,以提供绑定调用上下文为原料的功能。 但是提供的解决方案是不一般,它坚持了仿函数的空参数列表。 您将需要手工编写wrapperget_wrapperFunc为需要绑定,并给他们不同的名字各不同的函数签名。

我想提出对原材料绑定更广义的解决方案:

#include <iostream>
#include <memory>
#include <functional>
#include <cassert>

// Raw Bind - simulating auto storage behavior for static storage data
template <typename BindFunctor, typename FuncWrapper> class scoped_raw_bind
{
public:

   typedef scoped_raw_bind<BindFunctor, FuncWrapper> this_type;

   // Make it Move-Constructible only
   scoped_raw_bind(const this_type&) = delete;
   this_type& operator=(const this_type&) = delete;
   this_type& operator=(this_type&& rhs) = delete;

   scoped_raw_bind(this_type&& rhs): m_owning(rhs.m_owning)
   {
      rhs.m_owning = false;
   }

   scoped_raw_bind(BindFunctor b): m_owning(false)
   {
      // Precondition - check that we don't override static data for another raw bind instance
      if(get_bind_ptr() != nullptr)
      {
        assert(false);
        return;
      }
      // Smart pointer is required because bind expression is copy-constructible but not copy-assignable
      get_bind_ptr().reset(new BindFunctor(b));
      m_owning = true;
   }

   ~scoped_raw_bind()
   {
     if(m_owning)
     {
        assert(get_bind_ptr() != nullptr);
        get_bind_ptr().reset();
     }
   }

   decltype(&FuncWrapper::call) get_raw_ptr()
   {
      return &FuncWrapper::call;
   }

   static BindFunctor& get_bind()
   { 
      return *get_bind_ptr();
   }

private:

  bool m_owning;

  static std::unique_ptr<BindFunctor>& get_bind_ptr()
  {
     static std::unique_ptr<BindFunctor> s_funcPtr;
     return s_funcPtr;
  }

};

// Handy macro for creating raw bind object
// W is target function wrapper, B is source bind expression
#define RAW_BIND(W,B) std::move(scoped_raw_bind<decltype(B), W<decltype(B), __COUNTER__>>(B));

// Usage
///////////////////////////////////////////////////////////////////////////

// Target raw function signature
typedef void (*TargetFuncPtr)(double, int, const char*);

// Function that need to be called via bind
void f(double d, int i, const char* s1, const char* s2)
{
   std::cout << "f(" << d << ", " << i << ", " << s1 << ", " << s2 << ")" << std::endl;
}

// Wrapper for bound function
// id is required to generate unique type with static data for
// each raw bind instantiation.
// THE ONLY THING THAT YOU NEED TO WRITE MANUALLY!
template <typename BindFunc, int id = 0> struct fWrapper
{
   static void call(double d, int i, const char* s)
   {
      scoped_raw_bind<BindFunc, fWrapper<BindFunc, id>>::get_bind()(d, i, s);
   }
};

int main()
{
   using namespace std::placeholders;

   auto rf1 = RAW_BIND(fWrapper, std::bind(&f, _1, _2, _3, "This is f trail - 1"));
   TargetFuncPtr f1 = rf1.get_raw_ptr();
   f1(1.2345, 42, "f1: Bind! Bind!");

   auto rf2 = RAW_BIND(fWrapper, std::bind(&f, _1, _2, _3, "This is f trail - 2"));
   TargetFuncPtr f2 = rf2.get_raw_ptr();
   f2(10.2345, 420, "f2: Bind! Bind!");

   auto rf3 = RAW_BIND(fWrapper, std::bind(&f, _1, _2, _3, "This is f trail - 3"));
   TargetFuncPtr f3 = rf3.get_raw_ptr();
   f3(100.2345, 4200, "f3: Bind! Bind!");
}

据测试-见真人这里



Answer 4:

不,不是很容易。 问题是,一个函数指针具有信息的一个大块 - 函数的地址。 一种方法,都需要其与对象的地址,或者它可以被传递的对象地址作为参数。

有极其hackey方法可以做到这一点,但他们将是平台特定的。 和极其hackey。 正因如此,我会建议使用它们的全局变量来代替。

你知道如何做到这一点,如果有类的单一全局实例,对不对?



文章来源: convert std::bind to function pointer