我有以下代码(为简洁起见,进行了简化)。我正在制作简单“程序”的解释器和执行器,它基本上由命令和循环组成。
class Command
{
int code, arg; // whatever
};
class Loop;
using Statement = std::variant<std::monostate, Command, Loop>;
class Scope
{
std::vector<Statement> statements;
public:
Statement& appendCmd(const Command& = {}); // works
Statement& appendLoop(const Loop& = {}); // cannot convert from 'initializer list' to 'const Loop &'
Statement& appendLoop(const Loop& = Loop()); // use of undefined type 'Loop'
};
class Loop
{
Scope scope;
int iters;
};
问题是,
class Loop
需要为成员变量定义类Scope
,而class Scope
需要定义类Loop
来构造参数的默认值。
我该如何解决这个问题?另外,我不想让它们中的任何一个嵌套在其他任何一个中。
我之前已经遇到过这个问题,但是可以通过将方法定义移出头文件来忽略它。但是默认参数值必须位于标头中...
我想一种解决方案是:
#include <memory>
#include <variant>
#include <vector>
class Scope;
class Command
{
int code, arg; // whatever
};
class Loop
{
std::unique_ptr <Scope> scope;
int iters;
};
using Statement = std::variant<std::monostate, Command, Loop>;
class Scope
{
std::vector<Statement> statements;
public:
Statement& appendCmd(const Command& = {});
Statement& appendLoop(const Loop& = {});
};
但是@RetiredNinja 的评论非常相关。