1

这是我处理向 Lua 公开 C++ 类的一些实际代码,例如:

#include <lua5.1/lua.hpp>
#include <tuple>

//in actual code, lots of specializations of these C++<=>Lua's stack helper functions. Here it's just a sample.
template<typename T> T to(lua_State*, int);
template<> int to(lua_State* l, int i){
    return lua_tointeger(l, i);
}
template<typename T> void push(lua_State*, T);
template<> void push(lua_State* l, int val){
    lua_pushinteger(l, val);
}

//in actual code, placed in a header
template<typename T, T> class function_proxy{
    static_assert(sizeof(T)!=sizeof(T), "Error: function_proxy works with functions (duh)");
};

template<typename Return, typename... Args, Return(*func)(Args...)> class function_proxy<Return(*)(Args...), func>{
    static Return call(lua_State* l, Args... args){
        return func(args...);
    }
    template<typename... retrieved> static Return call(lua_State* l, retrieved... read){
        return call(l, read..., to<typename std::tuple_element<sizeof...(read), std::tuple<Args...> >::type >(l, 1+sizeof...(read)));
    }
public:
    static int wrapper(lua_State* l){
        push(l, call(l));
        return 1;
    }
};

//in actual code, inner class of a template class in another header
template<typename CT, CT> class member_helper{
    static_assert(sizeof(CT)!=sizeof(CT), "Error: member_helper works with members of T (duh)");
};
//Just one of the actual partial specializations, to combine constness and the return of void or non-void
template<typename Class, typename Return, typename... Args, Return(Class::*fun)(Args...)> struct member_helper<Return(Class::*)(Args...), fun>{
    static Return as_free(Class& obj, Args... args){
        return (obj.*fun)(args...);
    }
    static int worker(lua_State* l, Class& obj, bool is_const, bool write){
        if(write) throw "Cannot write a member function.";
        //ERROR HERE: template argument 2 is invalid. Not very helpful message.
        lua_pushcclosure(l, function_proxy<decltype(&as_free), &as_free>::wrapper, 0);
        return 1;
    }
};

struct Test{
    int test(int arg){ return arg*3; }
};

int test_as_free(int arg){ return arg*3; }

int main(){
    lua_State* l=luaL_newstate();
    Test t;
    //works fine
    lua_pushcclosure(l, function_proxy<decltype(&test_as_free), &test_as_free>::wrapper, 0);
    //does not work
    member_helper<decltype(&Test::test), &Test::test>::worker(l, t, false, false);
}

获取指针时代码失败function_proxy<decltype(&as_free), &as_free>::wrapper,即使在main. 我认为获取自由函数的指针而不是静态成员函数的指针没有任何区别。这是这个g++ 错误的一个实例(请注意,我使用它进行编译,-std=c++0x并且该错误似乎已在 C++11 中修复)?

4

2 回答 2

2

这是一个g++ 错误并已得到确认。

于 2012-04-16T18:33:09.853 回答
0

我还没有完全理解,但是您确定要 Class 为 decltype(&Test::test) 并返回为 &Test::test 吗?对我来说,它看起来应该是:

member_helper<Test, int>::worker

但是,如何通过在另一个之后添加一种类型的间接来从工作线变为非工作线呢?

于 2012-04-16T14:57:15.570 回答