gpt4 book ai didi

c++ - "using"语句中的自引用/循环引用

转载 作者:行者123 更新时间:2023-12-01 21:43:28 25 4
gpt4 key购买 nike

我尝试在程序中为动态变量定义变体类型,但我似乎无法使其存储将其作为类型返回的函数。

using Value = std::variant<Integer, Float, Function>;
using Function = std::function<Value()>;

这不会编译,因为 Function 需要在 Value 时定义,但 Function 依赖于 Value也是如此。我尝试通过将 Function 类型内联到变体模板列表中来解决此问题,但似乎 using 语句无法引用自身或向前声明。

到目前为止,我最好的解决方案是将 Function 定义为结构,以便我可以转发声明它。这可行,但看起来很老套,所以我想知道是否有更好的方法?

struct Function;
// define Value
struct Function : std::function<Value()> {};

为了澄清,std::function 被用作示例的一部分,因为我认为它会更容易地展示我正在尝试做的事情,而且我的黑客解决方案也需要它。如果可能的话,我更喜欢一种方法来让它与普通函数指针一起工作。

最佳答案

这是行不通的,因为您本质上想要创建的是:

std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<std::variant<Integer, Float, std::function<...()>>()>>()>>()>>()>>()>>()>>()>>()>>()>>()>>;

所以基本上你在类型声明中拥有无限递归。

您需要通过使用某种没有递归定义的类型来解决此问题,但使用转发的 struct直接像你建议的那样不是一个选择,因为 std::variant只允许完整类型。

你可以做的就是转发声明你的 struct ,然后在 std::unique_ptr<Function> 中使用您选择的容器/包装器/智能指针(例如 std::variant ) :

struct Function;
using Value = std::variant<Integer, Float, std::unique_ptr<Function>>;
struct Function : std::function<Value()> {};

关于c++ - "using"语句中的自引用/循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275569/

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