gpt4 book ai didi

c++ - 我怎样才能得到一个返回自身的 boost::function (或其他通用函数包装器)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:24:58 24 4
gpt4 key购买 nike

我最近迷上了 Erlang 的基于角色的并发模型的简单性,并且正在研究用 C++ 实现它的某些部分的想法。沿着这些思路,我也喜欢将有限状态机实现为一组表示状态的函数的想法,其中通过从一个函数到下一个函数的尾调用进行转换。

我想在 C++ 中尝试类似的东西。但是一个天真的实现很可能会遇到这样一个事实,即在我的编译器(带有 -O0 的 GCC 4.1)中进行尾调用最终会导致堆栈溢出。所以相反,我想做的是让每个状态/函数返回一个仿函数(下一个要进入的状态),并有一个底层循环,它只是顺序调用一个仿函数,然后调用返回的仿函数,然后调用仿函数因此返回,等等。类似的东西:

typedef ... context_t;

// A statefunctor is a functor which takes a context_t and
// returns a statefunctor
//
// FIXME: of course, this typedef won't compile.
typedef boost::function<statefunctor (context_t& )> statefunctor;

// NULL boost::function<> represents the exit condition.
static const statefunctor EXIT_FSM;

// primary loop which runs the FSM
void run_fsm(context_t& ctx, statefunctor initial_state)
{
while (initial_state)
{
initial_state=initial_state(boost::ref(ctx));
}
}

// states 'foo', 'bar', and 'baz';
statefunctor foo(context_t& ctx);
statefunctor bar(context_t& ctx, int inval);
statefunctor baz(context_t& ctx);

// State 'foo'
statefunctor foo(context_t& ctx)
{
// act somehow on the external context
int magic_number_1=ctx.get_magic_number();
int magic_number_2=ctx.get_magic_number();

// Always transition to 'bar'
return boost::bind(&bar, _1, magic_number_1-magic_number_2);
}

// State 'bar'
statefunctor bar(context_t& ctx, int inval)
{
inval+=ctx.get_magic_number(); // Act on external context somehow

// transition to foo or baz
if (inval>0) { return &foo; }
else { return &baz; }
}

// State 'baz'
statefunctor baz(context_t& ctx)
{
// Transition to foo or exit
if (ctx.get_magic_number()==5) {return EXIT_FSM;}
else {return &foo;}
}

int main()
{
context_t ctx;
// start the state machine in state 'foo'
run_fsm(ctx, &foo);
}

那么,我的问题是,如何定义 statefunctor?特别是,我希望它能够容纳任意仿函数(例如 boost::bind(...) 可能会创建),而不仅仅是函数指针。

注意:我正在使用 boost::bindboost::functionboost::ref 而不是他们的 std:: 对应物,因为我一直在使用不支持 C++11 的 GCC 4.1。在 C++03 中有效的解决方案表示赞赏;-)。

最佳答案

你不能通过 typedef 直接做到这一点,但你可以将 boost::function 包装在一个结构/类中(感谢 @R. Martinho Fernandes 制作我有这种洞察力):

#include <boost/function.hpp>

typedef int context_t;

struct statefunctor
: boost::function<statefunctor(context_t&)>
{
typedef boost::function<statefunctor(context_t&)> base_type;
statefunctor() : base_type(){}
template<class F>
statefunctor(F f) : base_type(f){}
};

Live example.

关于c++ - 我怎样才能得到一个返回自身的 boost::function (或其他通用函数包装器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12304438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com