I am writing some packaging code where an external library calls a C ++ function (using variable templates, etc.). The decisive point is that the external library requires a c-function, which, as a rule, will be beautiful, since it is legal:
LibraryFuncType fn = [](params) { ... }
While I can easily do this manually, I would like to automate the packaging with something like:
function_(context, "name", myfunc);
To do this, I will need a function similar to:
template <ReturnType, ParamTypes...> static void function_(Context &ctx, const std::string &name, std::function<ReturnType(ParamTypes...)> fn) { ctx.registerFunction(name, [fn](State *state) -> int { Context ctx(state); return apply_helper<sizeof..(ParamTypes)>::apply(ctx, fn); }); }
where the second parameter "ctx.registerFunction" is of type LibraryFuncType.
But this, of course, is problematic because lambda conversion is no longer legal due to the capture of 'fn'. However, if I did not capture 'fn', then I would not have access to it in lambda.
I think the only way to handle this is to have a static variable, but I donβt understand how best to implement it. My current solution:
template <typename ReturnType, typename... ParamTypes> struct function_helper { static std::function<ReturnType(ParamTypes...)> fn; function_helper(std::function<ReturnType(ParamTypes...)> _fn) { fn = _fn; } static void registerFn(Context &ctx, const std::string &name) { ctx.registerFn(name, [](state *state) -> int { Context ctx(state); return apply_helper<sizeof...<ParamTypes>>::apply(ctx, fn); }); } }; template <typename ReturnType, typename... ParamTypes> std::function<ReturnType(ParamTypes...)> function_helper<ReturnType, ParamTypes...>::fn; template <typename ReturnType, typename... ParamTypes> void function_(Context &ctx, const std::string &name, std::function<ReturnType(ParamTypes...)> fn) { function_helper<ReturnType, ParamTypes...> reg(fn); reg.registerFn(ctx, name); }
While technically this works, it is clearly dangerous (and hacked) because if I use the function_helper function for two functions with the same signature, it will set fn incorrectly for one of them.
Alternatively, I could make the same dangerous static variable by simply declaring the static variable in 'function_'. I made a class hoping this would lead to some understanding of the correct way to solve the problem.
Does anyone know of a better way to use a lambda that does not require capture (or, alternatively, a method of converting a lambda that performs capture into a c function)?