سؤال

How can boost::bind be used for a void pointer argument of a function?

boost::bind(foo, _1, boost::ref((void*)this))

is (obviously) not correct.

هل كانت مفيدة؟

المحلول

Bind is strong typed. Callbacks with void* are typically seen in C APIs, there is no need to use it otherwise:

struct Object { /* .... */ };

int some_callback(Object& o) // or e.g. a thread function
{
     // use o
}

You'd bind or call it as:

Object instance;
boost::function<int(Object&)> f = boost::bind(&some_callback, boost::ref(instance));

Of course, you can pass by value

int by_value(Object o) {}

f = boost::bin(&by_value, instance); // or `std::move(instance)` if appropriate

And if you insist by pointer (why?):

int by_pointer(Object* o) {}
f = boost::bin(&by_pointer, &instance);

If you want to be really really dirty (or you want to be signature compatible with that C API):

int by_void_ptr(void* opaque_pointer) {}
f = boost::bind(&by_void_ptr, &instance);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top