gpt4 book ai didi

c++ - 递归 typedef 函数定义:std::function 返回自己的类型

转载 作者:IT老高 更新时间:2023-10-28 22:13:51 24 4
gpt4 key购买 nike

我正在尝试实现状态机。状态由 callback_t 类型的函数表示:callback_t(int&) 返回相同类型的函数。

我不知道如何实现它,因为似乎不允许递归类型函数。

这是我尝试过的(作为玩具):

#include <stdio.h>
#include <functional>

typedef std::function< callback_t(int &) > callback_t ;
callback_t f1(int & i)
{
i++;
return f1;
}
callback_t f0(int & i)
{
if(i==0) i++;
return f1;
}
callback_t start(int & i)
{
i=0;
return f0;
}


int main(int argc, char **argv)
{
callback_t begin = start;
int i=0;

while(i<100)
begin = begin(i);

printf("hello world\n");
return 0;
}

错误:

C:/work/tests/tests/main.cpp:4:41: error: 'callback_t' was not declared in this scope
typedef std::function< callback_t(int &) > callback_t ;
^

有没有办法实现这种行为?

环境:win7、codelite、mingw 4.8.1

最佳答案

由于递归类型定义是不可能的,你可以声明一个带有函数的结构并隐式转换为它:

template< typename... T >
struct RecursiveHelper
{
typedef std::function< RecursiveHelper(T...) > type;
RecursiveHelper( type f ) : func(f) {}
operator type () { return func; }
type func;
};

typedef RecursiveHelper<int&>::type callback_t;

示例:http://coliru.stacked-crooked.com/a/c6d6c29f1718e121

关于c++ - 递归 typedef 函数定义:std::function 返回自己的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23737449/

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