Garmaine Staff asked 2 years ago

I've looking for how to cast class member to C-style callback.

Recentrly i found answer with special bind hack allows to bind class members to C-style callbacks:

I have this working code to bind function MyClass::f to C function f: But i want to avoid explicit passing cb_type as template parameter to c_bind function. In provided example CB has type void (*)(int) and Func template parameter has void (MyClass::*)(int) type.

template<typename CB, typename Func, typename... Params>
CB* c_bind(std::_Bind<Func(Params...)> function) {
    return Callback<typename ActualType<CB>::type, __COUNTER__, Func>::getCallback(function);

typedef void (cb_type)(int);

class MyClass {
    void f(int x) {
        std::cout << "Hello from MyClass::f(int), value: " << x << std::endl;

int main() {
    MyClass mc;

    auto f = c_bind<cb_type>(std::bind(&MyClass::f, mc, std::placeholders::_1));
    //                ^ how to avoid explicit callback type declaration here?

    return 0;

Also i found this piece of code ( for "unwrapping" some kind of functions.

bool ok = fu::is_unwrappable<decltype(&MyClass::f)>::value; // always false
// fu::unwrap_function<decltype(&MyClass::f)>::type::function_ptr blah; // won't compile

but it won't work by unknown to me reason.

My question is there any workaround to extract return type and args list from type with class-memeber pointer like void (MyClass::*)(int) and contruct C-like type void (*)(int) ?

Thank you for any help!