递归typedef函数定义:std :: function返回自己的类型 [英] Recursive typedef function definition : std::function returning its own type

查看:136
本文介绍了递归typedef函数定义:std :: function返回自己的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个状态机。该状态由类型 callback_t callback_t(int&)的函数表示,该函数返回相同类型的函数。

I am trying to implement a state-machine. The state is represented by a function of type callback_t : callback_t(int&) which returns a function of same type.

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

I dont know how to implement it since recursive typed function seems not to be allowed.

尝试(作为玩具):

#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 ;
                                       ^

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

Is there a way to implement this kind of behaviour ?

Env:win7,codelite,mingw 4.8.1

Env : win7, codelite, mingw 4.8.1

推荐答案

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

Since recursive type definition is not possible, you can declare a structure that carry the function and implicitly cast to it:

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

这篇关于递归typedef函数定义:std :: function返回自己的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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