gpt4 book ai didi

c++ - 将成员函数指针转换为普通函数指针

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:49 30 4
gpt4 key购买 nike

我正在使用可变调用模式 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)'

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

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

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

编辑:对于那些将我链接到 this question 的人, 这是不一样的。我不必将普通 C 函数指针传递给具有特定接口(interface)的现有 API。而且我并没有试图将成员函数绑定(bind)到特定对象。这个问题也不涉及可变参数调用或元组。

最佳答案

std::mem_fn做这个。

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

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++ - 将成员函数指针转换为普通函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34047732/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com