2
我试图将任何函数包装成一个函数,该函数需要一个参数(状态解释器)。如果我直接传递函数,一切运作良好。 但是,如果我换了一个额外的功能,我得到一个编译器错误。 请解释一下,我做错了什么。模板函数包装器
#include <iostream>
template <std::size_t... Is>
struct _indices {
template <template <size_t...> class Receiver>
using Relay = Receiver<Is...>;
};
template <std::size_t N, std::size_t... Is>
struct _indices_builder : _indices_builder<N-1, N-1, Is...> {};
template <std::size_t... Is>
struct _indices_builder<0, Is...> {
using type = _indices<Is...>;
};
struct lua_State
{};
template <typename Ret, typename... Args>
struct FunctionWrapperImpl {
template <size_t... Indices>
struct ImplementationNonVoid {
template <Ret (* func)(Args...)> static inline
int invoke(lua_State* state) {
func(10);
return 1;
}
};
using Implementation =
typename _indices_builder<sizeof...(Args)>::type::template Relay<
ImplementationNonVoid
>;
};
template <typename ToBeWrapped>
struct Wrapper {
};
template <typename Ret, typename... Args>
struct Wrapper<Ret (*)(Args...)>:
FunctionWrapperImpl<Ret, Args...>::Implementation {};
int test(int a)
{
std::cout<< a;
return 5;
}
typedef int (*lua_CFunction) (lua_State *L);
template <typename T>
lua_CFunction register_func(T fun)
{
lua_CFunction f =
(&Wrapper<decltype (fun)>::template invoke<T>); // Error
// no matches converting function 'invoke' to type 'lua_CFunction {aka int (*)(struct lua_State*)}'
//do somthing with f
return f;
}
int main(int argc, char *argv[])
{
lua_State s;
lua_CFunction t = (&Wrapper<decltype(&test)>::template invoke<&test>); // work
t(&s); // no problem
lua_CFunction t2 = register_func(&test);
t2(&s);
return 0;
}
完全编译错误。
main.cpp: In instantiation of 'int (* register_func(T))(lua_State*) [with T = int (*)(int); lua_CFunction = int (*)(lua_State*)]':
main.cpp:69:40: required from here
main.cpp:58:65: error: no matches converting function 'invoke' to type 'lua_CFunction {aka int (*)(struct lua_State*)}'
lua_CFunction f = (&Wrapper<decltype (fun)>::template invoke<T>);
^
main.cpp:25:7: note: candidate is: template<int (* func)(int)> static int FunctionWrapperImpl<Ret, Args>::ImplementationNonVoid<Indices>::invoke(lua_State*) [with Ret (* func)(Args ...) = func; long unsigned int ...Indices = {0ul}; Ret = int; Args = {int}]
int invoke(lua_State* state) {
感谢您的解释。一个小问题。是否有可能在Wrapper上编写一个包装函数,如果是这样的话? – a1ien
@ a1ien那么,一种解决方案可能是传递给创建的包装,除了函数类型直接指向你想在'invoke'方法内调用的函数,但它实际上取决于你的实际需要... –
I尝试这种模板 lua_CFunction register_func(退役(* FUNC)(参数数量...)) { \t lua_CFunction F = \t \t \t(&包装 ::模板调用); \t return f; } –
a1ien