【问题标题】:How can I define "recursive" function type in C++? [closed]如何在 C++ 中定义“递归”函数类型? [关闭]
【发布时间】:2020-12-06 01:59:14
【问题描述】:

我有任务,任务做了一些事情,如果必须再次调用它,则返回 True。

function<bool()> currentAction;

我原本打算用这样的东西来管理我当前的任务。

if (!currentAction())
    currentAction = []() { return false; };

然后我改变了主意,想要这样的东西

currentAction = currentAction();

但是什么是 CurrentAction 的合适类型?

它必须是一个返回一个函数的函数,该函数返回一个函数......

function<function<function<function<function<**[keep inserting here!]**()>()>()>()>()> currentAction;

很有可能尝试这样做不是一个好主意

【问题讨论】:

  • 只要函数返回true,为什么不运行一个while循环?
  • 我不太关注。你到底想在这里完成什么?你能补充更多细节吗? @J.Schultke 的建议我认为是最简单的。
  • @J.Schultke 该函数每秒调用一次
  • 你为什么改变主意?您认为新方法有什么好处? (如果没有好处,为什么要与语法搏斗?)

标签: c++ recursion types functional-programming return


【解决方案1】:

表达递归类型总是涉及到某个地方的包装器:

struct task : std::function<task()> { using std::function<task()>::function; };

但他们并没有错:

// "infinitely" recursive (UB when offset overflows, can use unsigned to make truly infinite)
task iota(int &out, int offset = 0) {
    return [&out, offset] {
        out = offset;
        return iota(out, offset + 1);
    };
}

这是一个最终“失败”的任务示例(返回一个空的task):

task limit(task t, int n) {
    if(n <= 0) return nullptr;
    else return [t = std::move(t), n]() { return limit(t(), n - 1); };
}

以下是您可以如何使用它们:

// prints integers [0, 42)
int main() {
    int i;
    task next = limit(iota(i), 42);
    while(next) {
        next = next();
        std::cout << i << "\n";
    }
}

Running on Godbolt

【讨论】:

    【解决方案2】:

    你可以创建类:

    struct Action
    {
        Action operator() { return next(); }
    
        std::function<Action()> next;
    };
    

    Demo

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多