将C ++ lambdas存储为二进制数据 [英] Storing C++ lambdas as binary data

查看:102
本文介绍了将C ++ lambdas存储为二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试扩展sqrat(松鼠绑定实用程序)以满足绑定鼠标到松鼠。

I'm currently attempting to extend sqrat (squirrel binding utility) to cater for binding lambdas to squirrel.

我遇到的问题是,虽然存储并且调用代码可以知道lambda的签名(这里是设置将执行lambda的函数的代码)

The issue I've got is that although the storing and recalling code can know about the lambda's signature (Here is the code to set up the function that will execute the lambda)

// Arg Count 0
template <class R, class Args, class Arity>
SQFUNCTION SqMemberLambdaFuncDetail(R result, 
                                    Args args,
                                    boost::mpl::integral_c<unsigned int, 1> arity)
{
    return &SqLambda<R>::template Func0<false>;
}

// Arg Count 1
template <class R, class Args, class Arity>
SQFUNCTION SqMemberLambdaFuncDetail(R result, 
                                    Args args, 
                                    boost::mpl::integral_c<unsigned int, 2> arity)
{
    return &SqLambda<R>::template Func1<boost::mpl::at_c<Args, 1>::type, 2, false>;
}

template <class F>
SQFUNCTION SqMemberLambdaFunc(F f)
{
    typedef boost::function_types::result_type<decltype(&F::operator())>::type result_t;
    typedef boost::function_types::function_arity< decltype(&F::operator())> arity_t;
    typedef boost::function_types::parameter_types< decltype(&F::operator())>::type args_t;
    result_t result;
    args_t args;
    arity_t arity;
    return SqMemberLambdaFuncDetail<result_t, args_t, arity_t>(result, args, arity);
}

lambda本身需要以匿名形式存储为二进制数据,

The lambda itself needs to be stored in an anonymous form, as binary data, and I can't seem to find a way to do that.

推荐答案

Lambdas不能保证是标准布局

Lambdas are not guaranteed to be standard layout (so looking at their bits is never legal), nor are their contents introspectable.

如果您想要可以序列化然后远程运行的代码,请使用脚本引擎。

If you want code that can be serialized and then run remotely, use a scripting engine. There are many, and some interact well with C++.

或者只是boost phoenix,这使得可反射的C ++ - 类型代码是lambda-esque。

Or just boost phoenix, which makes reflectible C++-esque code that is lambda-esque.

然而,如果你唯一的问题是存储一个带有签名 R(Args ...)的一般来说,只需使用 std :: function< R(Args ...)>

However if your only problem is storing a copy of a lambda with signature R(Args...) generically, simply use a std::function<R(Args...)>.

这篇关于将C ++ lambdas存储为二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆