我试图在* lua_CFunction *上创建一个简单的c ++包装器,它的定义如下:
// header
typedef int (*lua_CFunction) (lua_State* lua);
...
lua_CFunction wrap (std::function <int (Game* game)> function);
// implementation
lua_CFunction ScriptingInterface::wrap (std::function <int (Game* game)> function)
{
return [this, function] (lua_State* unused) -> int {
int n_args = function (this->game);
return n_args;
};
}
void ScriptingInterface::registerFunction (std::string name, std::function <int (Game* game)> function)
{
lua_register (lua, name.c_str (), wrap (function));
}
这个想法是创建这样的公共函数:
int setTitle (Game* interface)
{
const char* title = lua_tostring (interface->getScripts ()->getLuaState (), 1);
SDL_WM_SetCaption (title, NULL);
return 0;
}
与lua分享,如:
scripts->registerFunction ("setTitle", setTitle);
脚本是 ScriptingInterface
的一个实例尝试编译游戏时会出现问题。
./scripting/scripting_interface.cc: In member function ‘int (* ScriptingInterface::wrap(std::function<int(Game*)>))(lua_State*)’:
./scripting/scripting_interface.cc:40:2: error: cannot convert ‘ScriptingInterface::wrap(std::function<int(Game*)>)::<lambda(lua_State*)>’ to ‘int (*)(lua_State*)’ in return
./scripting/scripting_interface.cc:41:1: warning: control reaches end of non-void function [-Wreturn-type]
有人能告诉我这里做错了什么,因为AFAIK的代码应该编译没有任何问题吗?
答案 0 :(得分:2)
问题在于:
lua_CFunction ScriptingInterface::wrap(std::function<int(Game*)> function)
{
return [this, function] (lua_State* unused) -> int {
int n_args = function (this->game);
return n_args;
};
}
您正在尝试返回一个需要函数指针的lambda,但捕获 lambda无法转换为函数指针 - 而您的lambda正在捕获this
和{{ 1}}。根据C ++ 11标准的第5.1.2 / 6段:
没有lambda-capture 的lambda表达式的闭包类型具有公共非虚拟非显式const 转换函数指向函数,该函数具有与闭包类型相同的参数和返回类型 函数调用运算符。此转换函数返回的值应为函数的地址 当被调用时,它与调用闭包类型的函数调用操作符具有相同的效果。
不幸的是,除非您可以退回function
,否则您必须更改设计。