将成员函数指针转换为普通函数指针
问题描述:
我正在使用可变参数调用模式shown here。它对于普通的C函数来说工作正常。但我想用一个成员函数和一个明确具有实例指针作为第一个参数的元组来使用它。将成员函数指针转换为普通函数指针
我想是这样的:
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);
}
但它不能为指针类型转换:
cannot initialize a parameter of type 'void (*)(Object *, float, float)' with an lvalue of type 'void (Object::*)(float, float)'
在这种情况下,包装功能模板,使指针的类型有完全匹配。
template<typename Ret, typename...Args>
struct wrap{
static int wrapFunc(const string& name, Ret (*func)(Args...), lua_State* L)
{
...
}
};
如何我明确的成员函数指针转换成一个普通的函数指针取这个指针作为第一个参数?
编辑:对于那些已经链接到this question,这是不一样的。我不必传递一个简单的C函数指针到具有特定接口的现有API。而我不是试图将一个成员函数绑定到一个特定的对象。这个问题也不涉及可变的调用或元组。
答
std::mem_fn这样做。
为了使模板匹配:我不得不显式声明Args tuple中作为一类指针后跟参数组:
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;
}
};
的可能的复制[转换C++函数指针到c函数指针( http://*.com/questions/19808054/convert-c-function-pointer-to-c-function-pointer) –
或http://*.com/questions/19808054/convert-c-function-pointer-如果你喜欢 –
也许http://*.com/questions/4210710/cast-pointer-to-member-function-to-normal-pointer –