Rer*_*umu 7 c++ forward-declaration
我曾尝试在程序中为动态变量定义变量类型,但似乎无法使它存储将其返回为类型的函数。
using Value = std::variant<Integer, Float, Function>;
using Function = std::function<Value()>;
Run Code Online (Sandbox Code Playgroud)
由于Function需要在当时定义,因此不会编译Value,但也Function取决于它Value。我尝试通过将Function类型内联到变量模板列表中来解决此问题,但似乎using语句无法引用自身或进行正向声明。
到目前为止,我最好的解决方案是将其定义Function为结构,以便我可以对其进行声明。这行得通,但似乎太笨拙了,所以我想知道是否有更好的方法?
struct Function;
// define Value
struct Function : std::function<Value()> {};
Run Code Online (Sandbox Code Playgroud)
为了阐明这一点,它std::function被用作示例的一部分,因为我认为这样可以更轻松地展示我正在尝试做的事情,而对于我的hacky解决方案来说,这也是需要的。如果可能的话,我更希望有一种使用普通函数指针的方法。
这是行不通的,因为你本质上想要创建的是:
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()> {};
Run Code Online (Sandbox Code Playgroud)