将成员函数指针转换为普通函数指针 [英] Convert member function pointer to ordinary function pointer

查看:709
本文介绍了将成员函数指针转换为普通函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用可变参数调用模式

I am using the variadic call pattern shown here. It works fine for ordinary C functions. But I want to use it with a member function and a tuple that explicitly has an instance pointer as the first argument.

我尝试过这样的事情:

template<typename Ret, typename C, typename...Args>
int methodWrapper(const string& name, Ret (C::*func)(Args...), lua_State* L)
{
    return wrap<Ret,C*,Args...>::wrapFunc(name, func, L);
}

但是它无法转换指针类型:

But it fails to convert the pointer type:

cannot initialize a parameter of type 'void (*)(Object *, float, float)' with an lvalue of type 'void (Object::*)(float, float)'

在这种情况下,wrap函数是模板化的,因此指针的类型必须完全匹配.

In this case, the wrap function is templated, so the type of the pointer has to match exactly.

template<typename Ret, typename...Args>
struct wrap{
    static int wrapFunc(const string& name, Ret (*func)(Args...), lua_State* L)
    {
        ...
    }
};

如何将成员函数指针显式转换为以this指针作为第一个参数的普通函数指针?

How to I explicitly convert a member function pointer into an ordinary function pointer that takes the this pointer as its first argument?

对于那些已将我链接到此问题的人,不一样.我不必将普通的C函数指针传递给具有特定接口的现有API.而且我没有尝试将成员函数绑定到特定对象.这个问题也不涉及可变参数调用或元组.

for those that have linked me to this question, it is not the same. I do not have to pass a plain C function pointer to an existing API with a specific interface. And I am not trying to bind a member function to a specific object. This question also does not deal with variadic call or tuples.

推荐答案

std: :mem_fn 做到这一点.

为了使模板匹配:我必须将args元组显式声明为Class指针,后跟参数pack:

In order to make the template match: I had to explicitly declare the args tuple as a Class pointer followed by the parameter pack:

template<typename C, typename...Args>
struct wrapMethod<void,C,Args...>{
    static int wrap(const string& name, void (C::*func)(Args...), lua_State* L)
    {
        tuple<C*, Args...> args = cargs<C*,Args...>::getCArgs(L, name);

        //Return type (first template parameter) cannot be inferred.
        variadic_call<void>(mem_fn(func), args);

        return 0;
    }
};

这篇关于将成员函数指针转换为普通函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆